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

Managing filehandles within array of hashes in 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} created\n";
}

但后来,当我尝试向文件描述符打印一行时,出现以下错误:

String found where operator expected at ExecTasks.pl line 222, near ""$AoH[$i]{filefh}" "$row\n""
        (Missing operator before  "$row\n"?)
syntax error at ExecTasks.pl line 222, near ""$AoH[$i]{filefh}" "$row\n""
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} "$row\n";
            }
        }
    }

    close($fh);
}

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

顺便说一句,我在 Windows 的机器上工作,使用 perl 5.14.2

Perl 的 print 需要一个非常简单的表达式作为文件句柄 -- 根据 documentation:

If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted:

在你的情况下,你会使用:

print { $AoH[$i]{filefh} } "$row\n";

你也可以使用方法调用形式,但我可能不会:

$AoH[$i]{filefh}->print("$row\n");