【问题标题】:Why do I get a syntax error when I want to print to a handle in a hash key?当我想打印到哈希键中的句柄时,为什么会出现语法错误?
【发布时间】:2012-08-10 09:25:14
【问题描述】:

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

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;
        }
    }
}

在我遇到一些编译问题的代码中,我正在使用打印语句。

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""

谁能帮我理解错误?

【问题讨论】:

    标签: perl syntax-error filehandle


    【解决方案1】:

    第一个问题: 运行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;
    

    别忘了关闭文件句柄...

    【讨论】:

    • 3 参数形式的 open 也是一个不错的习惯:open ($fd, '>>', $_)
    • 你真的应该使用词法文件句柄来处理这种事情。
    【解决方案2】:

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

    如果您将句柄存储在数组或哈希中,或者通常在任何时候 您正在使用比裸字句柄或 普通的,无下标的标量变量来检索它,你将不得不 改为使用返回文件句柄值的块,在这种情况下 LIST 不能省略:

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

    【讨论】:

      【解决方案3】:

      也许是这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多