我是 Perl 的初学者。我不明白的是:
编写一个脚本,它可以:
- 使用逗号分隔符打印文件 $source 的行。
- 将格式化的行打印到输出文件。
- 允许在命令行中指定此输出文件。
代码:
my ( $source, $outputSource ) = @ARGV;
open( INPUT, $source ) or die "Unable to open file $source :$!";
问题:我不明白如何在命令行中指定在开始编写代码时输出文件的文本。
我会改用 shell 中的重定向运算符,例如:
script.pl input.txt > output.txt
那么这是一个简单的例子:
use strict;
use warnings;
while (<ARGV>) {
s/\n/,/;
print;
}
然后,您甚至可以将多个文件与script.pl input1.txt input2.txt ... > output_all.txt
. 或者一次只做一个文件,一个参数。
如果我理解你的问题是正确的,我希望这个例子能有所帮助。
程序:
use warnings;
use strict;
## Check input and output file as arguments in command line.
die "Usage: perl $0 input-file output-file\n" unless @ARGV == 2;
my ( $source, $output_source ) = @ARGV;
## Open both files, one for reading and other for writing.
open my $input, "<", $source or
die "Unable to open file $source : $!\n";
open my $output, ">", $output_source or
die "Unable to open file $output_source : $!\n";
## Read all file line by line, substitute the end of line with a ',' and print
## to output file.
while ( my $line = <$input> ) {
$line =~ tr/\n/,/;
printf $output "%s", $line;
}
close $input;
close $output;
执行:
$ perl script.pl infile outfile