5

我有一个文件名列表。我必须为每个名称创建一个文件,将行写入各种文件(无特定顺序),然​​后关闭它们。

我怎么能在 perl 中做到这一点?我设想类似下面的代码(它不会以这种形式工作并给出语法错误):

my @names = qw(foo.txt bar.txt baz.txt);
my @handles;

foreach(@names){
  my $handle;
  open($handle, $_);
  push @handles, $handle; 
}

# according to input etc.:
print $handles[2] "wassup";
print $handles[0] "hello";
print $handles[1] "world";
print $handles[0] "...";

foreach(@handles){
  close $_;
}

我怎样才能做到这一点?

4

2 回答 2

15

的文件句柄参数print必须是一个裸字、一个简单的标量或一个块。所以:

print { $handles[0] } ...

这在perldoc -f print中进行了解释。相同的限制通常适用于间接对象语法,以及确定何时 <> 是 readline 操作,而不是 glob 操作。

于 2009-06-09T03:50:31.983 回答
3

这是我的做法(未经测试,但我很确定它很好):

use IO::File;

# ...
my @handles = map { IO::File->new($_, 'w') } @names;

$handles[2]->print("wassup");
# ...

它是面向对象的,它有一个更干净的界面,而且你不必担心关闭它们,因为当数组超出范围时它会死掉。

于 2009-06-09T04:00:15.293 回答