当我想要打印到散列键中的句柄时,为什么会出现语法错误?

时间:2012-08-10 09:25:14

标签: perl syntax-error filehandle

我有代码,它将当前目录中文件的所有文件句柄存储为哈希值。键是文件的名称。

my %files_list;    #this is a global variable.
sub create_hash() {
    opendir my $dir, "." or die "Cannot open directory: $!";
    my @files = readdir $dir;
    foreach (@files) {
        if (/.text/) {
            open(PLOT, ">>$_") || die("This file will not open!");
            $files_list{$_} = *PLOT;
        }
    }
}

我在我的代码中使用print语句,我面临一些编译问题。

my $domain = $_;
opendir my $dir, "." or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach (@files) {
    if (/.text/ && /$subnetwork2/) {
        print $files_list{$_} "$domain";    #this is line 72 where there is error.
    }
}
closedir $dir;

编译错误如下:

String found where operator expected at process.pl line 72, near "} "$domain""
        (Missing operator before  "$domain"?)
syntax error at process.pl line 72, near "} "$domain""

有人可以帮我理解这个错误吗?

3 个答案:

答案 0 :(得分:2)

第一个问题: 运行create_hash子例程后,所有密钥中都会%files_list填充*PLOT

所有print {$files_list{$_}} "$domain";都会打印到上次打开的文件中 溶液:

-open(PLOT,">>$_") || die("This file will not open!");
-$files_list{$_}=*PLOT;
+open($files_list{$_},">>$_") || die("This file will not open!");
第二个问题: 在打印之前不要检查文件描述符是否存在 溶液:

-if(/.text/ && /$subnetwork2/)
-{
-    print $files_list{$_} "$domain";#this is line 72 where there is error.
+if(/.text/ && /$subnetwork2/ && exists $files_list{$_})
+{
+    print {$files_list{$_}} $domain;

并且不要忘记关闭文件句柄...

答案 1 :(得分:2)

也许你应该阅读documentation for print。最后一段说:

  

如果您将句柄存储在数组或散列中,或者通常在任何时候存储   你使用的任何表达都比一个简单的句柄或一个更复杂   用于检索它的普通,未订阅的标量变量,您将不得不这样做   使用一个块来代替返回文件句柄值,在这种情况下   列表不得省略:

print { $files[$i] } "stuff\n";
print { $OK ? STDOUT : STDERR } "stuff\n";

答案 2 :(得分:1)

也许就是这样:

print {$files_list{$_}} "$domain";