Perl 读入前5行,打印指定行
我试图读入输入文件的前5行,并仅打印命令行中提供给perl脚本的一行(在本例中为第4行)。我在将当前行号与指定行号进行比较时遇到一些问题 以下是我的perl脚本的重要部分:Perl 读入前5行,打印指定行,perl,Perl,我试图读入输入文件的前5行,并仅打印命令行中提供给perl脚本的一行(在本例中为第4行)。我在将当前行号与指定行号进行比较时遇到一些问题 以下是我的perl脚本的重要部分: # Variables my $sInputFile = $ARGV[0]; my $sOutputFile = $ARGV[1]; my $sRowExtractNumber = $ARGV[2]; # Open-Close / Exceptions open(my $in, "<", $sInputFile) o
# 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;
}
}
#变量
my$sInputFile=$ARGV[0];
my$sOutputFile=$ARGV[1];
我的$sRowExtractNumber=$ARGV[2];
#打开/关闭/异常
打开(my$in,“,$sOutputFile)或死亡“无法打开输入文件:$sInputFile\n”;
#剧本
而(){
如果(1..5){
如果$\=$sRowExtractNumber,则打印$out$\uu;
}
}
我没有收到任何错误,但是没有任何内容被打印到$out
文件中
我怎样才能实现我的目标
谢谢。该
$。
变量是当前输入行号。我想你是误用了$\uu
尽管您可能希望事先验证输入,但无需检查行号是否为5或更少,以及是否与请求的行匹配
您必须始终在每个模块的顶部使用严格的和警告。这是一个简单的措施,可以提醒您注意许多琐碎的错误,否则您很容易忽略这些错误。您应该使用小写字母作为本地标识符:大写字母用于全局字符,例如包名
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;
}
}
使用严格;
使用警告;
my($input\u file、$output\u file、$row\u extract\u number)=@ARGV;
如果$row\U extract\U number<1或$row\U extract\U number>5,则模具“线号必须为5或更少”;
打开我的$in、、$output_文件或死亡qq{无法为输出打开“$output_文件:$!}
而(){
如果($。==$行\u提取\u编号){
打印$out$;
最后的
}
}
请欣赏答案上方的提示。我会记住这些。