3

Perl 中有没有办法以编程方式生成文件句柄?

我想同时打开十个文件并使用由(CONST NAME + NUMBER)组成的文件句柄写入它们。例如:

 print const_name4  "data.."; #Then print the datat to file #4
4

3 回答 3

9

您可以将文件句柄直接粘贴到未初始化的数组插槽中。

my @handles;
for my $number (0 .. 9) {
    open $handles[$number], '>', "data$number";
}

不要忘记打印到数组中的句柄的语法略有不同:

print $handles[3] $data;    # syntax error
print {$handles[3]} $data;  # you need braces like this
于 2010-01-10T17:29:36.223 回答
5

使用一点IO::Filemap你也可以这样做:

use IO::File;

my @files = map { IO::File->new( "file$_", 'w' ) } 0..9;

$files[2]->print( "writing to third file (file2)\n" );
于 2010-01-11T09:10:29.010 回答
3

如今,您可以将文件句柄分配给标量(而不是使用表达式(如您的示例那样)),因此您可以创建一个数组并用它们填充它。

my @list_of_file_handles;
foreach my $filename (1..10) {
    open my $fh, '>', '/path/to/' . $filename;
    push $list_of_file_handles, $fh;
}

当然,您可以改用可变变量,但它们是一种讨厌的方法,而且我从未见过使用数组或散列不是更​​好的选择。

于 2010-01-10T17:19:45.823 回答