在perl中,如何打印到运行时解析文件句柄的文件?

时间:2011-01-26 11:05:45

标签: perl

我有以下代码:

use strict;
my $org_file_hash = {
      'S6' => '/path/to/file/filename.txt_S6',
      'S8' => '/path/to/file/filename.txt_S8',
      'S2' => '/path/to/file/filename.txt_S2',
      'S0' => '/path/to/file/filename.txt_S0',
      'S00' => '/path/to/file/filename.txt_S00'
    };
my $filehandles;
for(keys %{$org_file_hash})
{
    my $key=$_;
    open(my $key,">",$org_file_hash->{$key}) || die "Cannot open ".$org_file_hash->{$key}." for writing: $!";
    push(@{$filehandles},$key);
}

在代码的后半部分,我得到$ org为“S2”。

my $org="S2";

基于$ org我将决定我需要打印的文件,在这种情况下它是/path/to/file/filename.txt_S2。

为实现这一目标,我正在做以下事情,但它不起作用:

my $org="S2";
print {$org} "hello world\n";

我收到以下错误:

Can't use string ("S2") as a symbol ref while "strict refs" in use at new_t.pl line 22.

请帮忙。

2 个答案:

答案 0 :(得分:3)

使用$filehandles作为哈希(或hashref)而不是arrayref,如下所示:

my $filehandles = {};
for my $key (keys %{$org_file_hash})
{
    # my $key=$_;     # redundant
    open( my $fh, '>', $org_file_hash->{$key} )
        or die "Cannot open ".$org_file_hash->{$key}." for writing: $!";
    $filehandles->{$key} = $fh;
}

# later...
my $org = 'S2';
print { $filehandles->{$org} } "Hello, world.\n";

最后,不要忘记迭代keys %{$filehandles}close您的open ed文件。

答案 1 :(得分:1)

使用哈希:

my $filehandles = {};

for my $key (keys %{$org_file_hash}) {
    open my $fh, ">", $org_file_hash->{$key} or die $!;    
    $filehandles->{$key} = $fh;    
}
my $org="S2";
print {$filehandles->{$org}} "hello world\n";

顺便说一句,如果您使用open my $fh, ...形式的open$fh应该是未定义的。否则,其值将用作所需的真实文件句柄的名称。这被视为符号引用,因此脚本不会在“use strict 'refs'”下编译。