如何将特定的数组值赋给$skip?我会从特定行开始从a.txt或b.txt读取数据(88用于a.txt,64用于b.txt)
#!/usr/bin/perl
# Libraries
use strict;
use warnings;
# Main script
my @filename = ('a.txt', 'b.txt');
my @nrows = ('88', '64');
foreach my $file_input(glob("*.txt")) {
open my $fh, '<', $file_input or die "can't read open $IN_FILE";
for my $i (0 .. $#nrows) {
if ( $file_input eq $filename[$i] ) {
my $skip = $nrows[$i];
}
}
$/ = "\n\n"; # record separator
while( <$fh> ) {
next unless '$skip' .. undef;
my @lines = split /\n\n/;
**... some manipulations ...**
}
close ($fh);
}我收到以下错误:
Use of uninitialized value $skip in concatenation (.) or string at ./exercise.n24.pl line 14, <$fh> chunk 11.我在过去的4个小时里做了很多测试,我不知道我哪里错了
发布于 2018-08-01 01:55:23
我可以在这里看到几个明显的错误。
您可以在立即结束的块中声明$skip。
if ( $file_input eq $filename[$i] ) {
my $skip = $nrows[$i];
}所以你永远看不到$skip的价值。
然后,当您尝试访问$skip时,您可以将其放在单引号中。并且变量不会在单引号中展开,因此Perl仅将其视为五个字符$、s、k、i和p。
但我认为这两者都不能解释你所看到的错误。示例代码中的哪一行是第14行。
如果你给我们一个我们可以运行的代码样本,它对我们会更有用。
我会建议另一种方法,但我担心这真的不清楚你想要做什么。
发布于 2018-08-01 02:40:44
您得到的错误是因为在您的代码中,您试图在声明它的作用域之外使用$skip。
但在更广泛的层面上,您似乎只想跳过特定数量的行,这取决于文件名。你应该使用散列而不是并行数组。
use strict;
my %lines_to_skip = (
'a.txt' => 88,
'b.txt' => 64
);
for my $file (glob("*.txt")) {
my $skip = $lines_to_skip{$file};
open my $fh, '<', $file;
# local $/ = "\n\n"; # note that this would read the file in paragraph mode
while (<$fh>) {
next unless $. > $skip;
# do something
}
}https://stackoverflow.com/questions/51619200
复制相似问题