我希望用ARGV指定的每个(小)文件都在其自己的数组中读取。如果我不测试$ARGV
,<>
会将所有文件包含在一个表中。有更好/更短/更简单的方法吗?
# invocation: ./prog.pl *.txt
@table = ();
$current = "";
while (<>)
{
if ($ARGV ne $current)
{
@ar = ();
$current = $ARGV;
if ($current)
{
push @table, \@ar;
}
}
push @ar;
}
最佳答案
请始终将use strict
和use warnings
放在程序顶部,并使用my
声明接近其第一使用点的变量。
最简单的方法是在ARGV
文件句柄上测试文件结尾,以确定何时要打开新文件。
此代码使用状态变量$eof
记录是否已完全读取先前的文件,以避免在到达@table
列表的末尾时不必要地向@ARGV
数组添加新元素。
use strict;
use warnings;
my @table;
my $eof = 1;
while (<>) {
chomp;
push @table, [] if $eof;
push @{$table[-1]}, $_;
$eof = eof;
}
@Alan Haggai Alavi's在文件末尾增加索引而不是设置标志的想法要好得多,因为它避免了在每个文件的开头显式创建一个空数组的需要。
这是我对他的解决方案的看法,但这完全取决于Alan的职位,他应该为此而功劳。
use strict;
use warnings;
my @table;
my $index = 0;
while (<>) {
chomp;
push @{$table[$index]}, $_;
$index++ if eof;
}