在 perl 中管理哈希数组中的文件句柄



>我有一个哈希数组,我按以下方式填写:

# Array of hashes, for the files, regexps and more.
my @AoH;
push @AoH, { root => "msgFile", file => my $msgFile, filefh => my $msgFilefh, cleanregexp => s/.+Msg:/Msg:/g, storeregexp => '^Msg:' };

这是条目之一,我有更多这样的条目。并且一直使用哈希的每个键值对来创建文件,从文本文件中清除行等等。问题是,我通过以下方式创建了文件:

# Creating folder for containing module files.
my $modulesdir = "$dir/temp";
# Creating and opening files by module.
for my $i ( 0 .. $#AoH )
{
# Generating the name of the file, and storing it in hash.
$AoH[$i]{file} = "$modulesdir/$AoH[$i]{root}.csv";
# Creating and opening the current file.
open ($AoH[$i]{filefh}, ">", $AoH[$i]{file}) or die "Unable to open file $AoH[$i]{file}n";
print "$AoH[$i]{filefh} createdn";
}

但是后来,当我尝试将一行打印到文件描述符时,我收到以下错误:

String found where operator expected at ExecTasks.pl line 222, near ""$AoH[$i]{filefh}" "$rown""
(Missing operator before  "$rown"?)
syntax error at ExecTasks.pl line 222, near ""$AoH[$i]{filefh}" "$rown""
Execution of ExecTasks.pl aborted due to compilation errors.

而且,这是我尝试打印到文件的方式:

# Opening each of the files.
foreach my $file(@files)
{
# Opening actual file.
open(my $fh, $file);
# Iterating through lines of file.
while (my $row = <$fh>)
{
# Removing any new line.
chomp $row;
# Iterating through the array of hashes for module info.
for my $i ( 0 .. $#AoH )
{
if ($row =~ m/$AoH[$i]{storeregexp}/)
{
print $AoH[$i]{filefh} "$rown";
}
}
}
close($fh);
}

我尝试打印到文件的方式有什么问题?我尝试打印文件句柄的值,并且能够打印它。另外,我成功地打印了带有storeregexp的匹配项。

顺便说一下,我正在使用 perl 5.14.2 在一台装有 Windows 的机器上工作

Perl 的print期望一个非常简单的表达式作为文件句柄 - 根据文档:

如果要将句柄存储在数组或哈希中,或者通常每当使用比裸词句柄或普通的无下标标量变量更复杂的表达式来检索它时,都必须使用返回 filehandle 值的块,在这种情况下,可能不会省略 LIST:

在您的情况下,您将使用:

print { $AoH[$i]{filefh} } "$rown";

您也可以使用方法调用表单,但我可能不会:

$AoH[$i]{filefh}->print("$rown");

最新更新