【问题标题】:Managing filehandles within array of hashes in perl在 perl 中管理哈希数组中的文件句柄
【发布时间】:2020-05-20 01:37:10
【问题描述】:

我有一个哈希数组,我用以下方式填充它:

# 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 filehandle


    【解决方案1】:

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

    如果您将句柄存储在数组或散列中,或者一般来说,当您使用比裸字句柄或普通的无下标标量变量更复杂的表达式来检索它时,您将不得不使用返回的块文件句柄值,在这种情况下不能省略 LIST:

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

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

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

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

    【讨论】:

    • Re "但我可能不会",请注意这是 Jim Davis 表达他们的个人风格偏好,而不是反对使用第二种方法。这两种方法都很好。
    • @ikegami 我只测试了第一个并且工作得很好。出于可读性目的,我将其保留。 (可能是我受到了影响,呵呵)。
    • @ikegami - 虽然你是对的(回复:个人偏好),但我不确定第二种形式在习惯上“正确”的程度如何,因为我认为我从未见过它在野外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2012-07-13
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多