我正在尝试读取输入文件的前5行,并且只打印从命令行提供给perl脚本的单行(在本例中为第4行)。我在将当前行号与指定的行号进行比较时遇到了一些麻烦。
以下是我的perl脚本的重要部分:
# Variables
my $sInputFile = $ARGV[0];
my $sOutputFile = $ARGV[1];
my $sRowExtractNumber = $ARGV[2];
# Open-Close / Exceptions
open(my $in, "<", $sInputFile) or die "cannot open output file: $sOutputFile\n";
open(my $out, ">", $sOutputFile) or die "cannot open input file: $sInputFile\n";
# Script
while (<$in>) {
if (1..5) {
print $out $_ if $_ == $sRowExtractNumber;
}
}
我没有收到任何错误,但没有任何内容打印到$out
文件。
我如何实现目标?
感谢。
答案 0 :(得分:0)
$.
变量是当前输入行号。我认为你错误地使用了$_
。
虽然您可能希望事先验证输入,但无需检查行号是否为和的行号是否与请求的行匹配。
您必须始终 use strict
和use warnings
位于每个模块的顶部。这是一个简单的措施,可以提醒您很多容易忽视的琐碎错误。并且您应该使用小写字母表示本地标识符:大写字母保留用于全局变量,例如包名称。
use strict;
use warnings;
my ($input_file, $output_file, $row_extract_number) = @ARGV;
die "Line number must be five or less" if $row_extract_number < 1 or $row_extract_number > 5;
open my $in, '<', $input_file or die qq{Cannot open "$input_file" for input: $!}
open my $out, '>', $output_file or die qq{Cannot open "$output_file" for output: $!}
while (<$in>) {
if ($. == $row_extract_number) {
print $out $_;
last;
}
}