我有一个哈希数组,我按以下方式填写:
# 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:' };
Run Code Online (Sandbox Code Playgroud)
这是其中一个条目,我有更多这样的。并且一直使用散列的每个键值对来创建文件、清理文本文件中的行等等。问题是,我通过以下方式创建了文件:
# 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";
}
Run Code Online (Sandbox Code Playgroud)
但是后来,当我尝试将一行打印到文件描述符时,出现以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
而且,这是我尝试打印到文件的方式:
# 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);
}
Run Code Online (Sandbox Code Playgroud)
我尝试打印到文件的方式有什么问题?我尝试打印文件句柄的值,并且能够打印它。此外,我成功打印了 storeregexp 的匹配项。
顺便说一句,我在一台装有 Windows 的机器上工作,使用 perl 5.14.2
Perlprint需要一个非常简单的表达式作为文件句柄——根据文档:
如果您将句柄存储在数组或散列中,或者一般来说,当您使用任何比裸字句柄或普通的、无下标的标量变量更复杂的表达式来检索它时,您将不得不使用返回文件句柄值的块相反,在这种情况下,不能省略 LIST:
在你的情况下,你会使用:
print { $AoH[$i]{filefh} } "$row\n";
Run Code Online (Sandbox Code Playgroud)
您也可以使用方法调用形式,但我可能不会:
$AoH[$i]{filefh}->print("$row\n");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |