如何通过Perl打开和编辑文件?

时间:2019-07-13 16:21:36

标签: file perl editing

我想给用户输入(多行)并将多行输出打印到用户使用

命名的新文件中

我已经尝试过

say "enter filename";
chomp(my $filename = <STDIN>);
open my $fn, '>', $filename;
say "enter contents";
print "> ";
chomp(my $contents = <STDIN>);
print {$fn} $contents;
close $fn;

但这仅适用于一行。

say "enter filename";
chomp(my $filename = <STDIN>);
open my $fn, '>', $filename;
say "enter contents";
print "> ";
chomp(my $contents = <STDIN>);
print {$fn} $contents;
close $fn;

但是多行并创建一个新文件,而不编辑旧文件

它要么不创建文件,不编辑文件,要么什么都不做。

2 个答案:

答案 0 :(得分:3)

键入新文件或在现有文件中添加行

use warnings;
use strict;
use feature 'say';

my $filename = shift;  # Better use a module (eg. Getopt::Long)

if (not $filename) { 
    $filename = get_filename();
}
elsif (-f $filename) {
    say "Appending to file \"$filename\".";
}
elsif (-e $filename and not -f $filename) {
    say "The \"$filename\" exists but is not a plain file.";
    $filename = get_filename();
}
else {
    say "Creating file \"$filename\"";
}

open my $fh, '>>', $filename or die "Can't open $filename: $!";
say "\nEnter lines to add. Press Ctrl-D when done.\n";

print ">  ";
while (my $line = <STDIN>) {
    print $fh $line;
    print ">  ";
}  

sub get_filename {
    print "Enter the name for a file to create/edit:  ";
    chomp (my $filename = <STDIN>);
    while (-e $filename and not -f $filename) { 
        say "The \"$filename\" exists but is not a plain file.";
        print "Enter the name for a file to create/edit:  ";
        chomp ($filename = <STDIN>);
    }   
    usage() if not $filename;
    return $filename;
}
sub usage { 
    say STDERR "Usage: $0 [filename]";
    exit;
}

请注意,用户输入的实际书写可以简单地写为

 print $fh $_ while <STDIN>;

其余所有是用户输入,检查等的管理。可以根据可能的使用细节以多种方式组织。以上是简单的说明,请根据需要进行更改和调整。

答案 1 :(得分:0)

这里是一个示例,可让您通过按CTRL-C退出循环:

use feature qw(say);
use strict;
use warnings;

STDOUT->autoflush(1);
say "enter filename";
chomp(my $filename = <STDIN>);
open my $fh, '>', $filename or die "Could not open file '$filename': $!";
{
    local $SIG{INT} = sub { die "SIGINT" };
    say "enter contents (CTRL-C to exit)";
    eval {
        while (1) {
            print "> ";
            my $contents = <STDIN>;  # do not need chomp here
            print $fh $contents;
        }
    };
    close $fh;
    say "\nDone. Saved file '$filename'";
}