如何在每次循环迭代时写入不同的输出文件? (Perl)
How to write on different output files at each iteration of loop? (Perl)
我在 Perl 中有一个名为 data
的散列的散列的散列,具有一级键:F、NF 和 S(基本上,%data={'F' => ..., 'NF' => ..., 'S' => ...}
)
在我的代码开头,我打开了 3 个输出句柄:
open (my $fh1, ">>", $filename1) or die "cannot open > $filename1: $!";
open (my $fh2, ">>", $filename2) or die "cannot open > $filename2: $!";
open (my $fh3, ">>", $filename3) or die "cannot open > $filename3: $!";
然后,当我的代码 运行s 时,它填充哈希的哈希,最后,我想打印每个键的哈希结果哈希 'F', 'NF' 和 'S' 到一个单独的文件中(由我在开头定义的三个文件句柄标识。)我不太确定如何执行此操作。我尝试了以下操作:在我打印哈希的 foreach
循环之前,我定义了
my @file_handles=($fh1, $fh2, $fh3);
my $handle_index=0;
并且在哈希的每次迭代中,我使用
写入文件
print $file_handles[$handle_index] "$stuff\n";
但是,当我尝试 运行 代码时,它告诉我 string found where operator expected
据我了解,我没有正确地告诉他应该使用哪个文件句柄。有什么建议吗?
我似乎能够通过使用存储在数组中的文件句柄来重现您的问题。也许这是不可能的,尽管我可以发誓我以前见过它被使用过。
>perl -lwe"open $x, '>', 'a.txt' or die $!; @x = ($x); print $x[0] 'asd';"
String found where operator expected at -e line 1, near "] 'asd'"
(Missing operator before 'asd'?)
syntax error at -e line 1, near "] 'asd'"
Execution of -e aborted due to compilation errors.
使用哈希也是如此。可能的解决方法是:
您可以跳过间接对象表示法并使用:
$file_handles[$index]->print("$stuff\n")
或者您可以使用 Perl 风格的循环来代替打印:
for my $fh (@file_handles) {
print $fh "$stuff\n";
}
间接对象表示法是将对象(在您的情况下是文件句柄)放在函数调用之前,如下所示:
my $obj = new Module;
而不是传统的:
my $obj = Module->new;
中有关间接宾语表示法的更多信息
除了文件句柄的简单标量或裸字外,您必须将文件句柄括在大括号中:
print { $file_handles[$handle_index] } "stuff to print";
注意文件句柄部分后仍然没有逗号。
我在 Perl 中有一个名为 data
的散列的散列的散列,具有一级键:F、NF 和 S(基本上,%data={'F' => ..., 'NF' => ..., 'S' => ...}
)
在我的代码开头,我打开了 3 个输出句柄:
open (my $fh1, ">>", $filename1) or die "cannot open > $filename1: $!";
open (my $fh2, ">>", $filename2) or die "cannot open > $filename2: $!";
open (my $fh3, ">>", $filename3) or die "cannot open > $filename3: $!";
然后,当我的代码 运行s 时,它填充哈希的哈希,最后,我想打印每个键的哈希结果哈希 'F', 'NF' 和 'S' 到一个单独的文件中(由我在开头定义的三个文件句柄标识。)我不太确定如何执行此操作。我尝试了以下操作:在我打印哈希的 foreach
循环之前,我定义了
my @file_handles=($fh1, $fh2, $fh3);
my $handle_index=0;
并且在哈希的每次迭代中,我使用
写入文件print $file_handles[$handle_index] "$stuff\n";
但是,当我尝试 运行 代码时,它告诉我 string found where operator expected
据我了解,我没有正确地告诉他应该使用哪个文件句柄。有什么建议吗?
我似乎能够通过使用存储在数组中的文件句柄来重现您的问题。也许这是不可能的,尽管我可以发誓我以前见过它被使用过。
>perl -lwe"open $x, '>', 'a.txt' or die $!; @x = ($x); print $x[0] 'asd';"
String found where operator expected at -e line 1, near "] 'asd'"
(Missing operator before 'asd'?)
syntax error at -e line 1, near "] 'asd'"
Execution of -e aborted due to compilation errors.
使用哈希也是如此。可能的解决方法是:
您可以跳过间接对象表示法并使用:
$file_handles[$index]->print("$stuff\n")
或者您可以使用 Perl 风格的循环来代替打印:
for my $fh (@file_handles) {
print $fh "$stuff\n";
}
间接对象表示法是将对象(在您的情况下是文件句柄)放在函数调用之前,如下所示:
my $obj = new Module;
而不是传统的:
my $obj = Module->new;
中有关间接宾语表示法的更多信息
除了文件句柄的简单标量或裸字外,您必须将文件句柄括在大括号中:
print { $file_handles[$handle_index] } "stuff to print";
注意文件句柄部分后仍然没有逗号。