我想从目录中读取多个文件并将每个值存储在一个唯一的变量中,以便稍后我可以使用描述性标题将其打印出来.文件名具有公共前缀,但是是唯一的.
我知道如何打开一个文件,但有没有一种有效的方法来打开许多文件?或者我是否为每个人打开了唯一的文件句柄?谢谢.
文件名有一个共同的前缀,如(abc_*):
abc_foo_dir
abc_bar.dat1.20101208
abc_bar.dat2.20101209
Run Code Online (Sandbox Code Playgroud)
打开第一个文件的示例:
open FILE, "< /home/test/data/abc_foo_dir";
while (<FILE>) {
my $line = $_;
chomp($line);
print "$line\n";
}
close FILE;
Run Code Online (Sandbox Code Playgroud)
你说"将每个值存储在一个唯一的变量中",但这实际上是一个哈希表的任务.
my %file_contents;
foreach my $filename (qw(...filenames here... or use a glob to fetch them))
{
open my $fh, '<', $filename or die "Cannot open $filename: $!";
local $/; # enable slurp mode
# read in the entire contents of the file and store in the hash
$file_contents{$filename} = <$fh>;
# this would close automatically when going out of scope,
# but it's nice to be explicit
close $fh;
}
Run Code Online (Sandbox Code Playgroud)
您可以稍后迭代所有键keys %file_contents,但如果您不熟悉如何使用哈希,我建议您阅读perldoc perldata和perldoc perlsyn.