【问题标题】:perl syntax error at wordlist.pl line 11, near ") $fh"在 wordlist.pl 第 11 行,") $fh" 附近出现 perl 语法错误
【发布时间】:2013-11-08 01:47:26
【问题描述】:
my $fn= "words.txt";
open ($fn), $file;
if (! -e "$fh") $fh="STDIN";
while (<$fn>){;
    my $total_words = @words; #All word count
    my %count;
    $count{$_}++ for @words; # Here are the counts
    my $uniq_words  = scalar keys %count; # Number of uniq words
}
# Print sorted by frequency

print "$_\t$count{$_}" for (sort { $count{$b} <=> $count{$a} } keys %count);

close FILE;
exit 0

我收到此错误:

Scalar found where operator expected at wordlist.pl line 8, near ") $fh"
        (Missing operator before $fh?)
syntax error at wordlist.pl line 8, near ") $fh"
Execution of wordlist.pl aborted due to compilation errors.

请帮忙

【问题讨论】:

    标签: perl syntax operator-keyword scalar


    【解决方案1】:
    open ($fn), $file;
    

    去掉这里的括号。

    第一个参数是文件句柄,第二个是文件名。您使用$fn 作为文件名和文件句柄,而$file 从未定义。

    if (! -e "$fh") $fh="STDIN";
    

    你不能像这样在一个方块周围去掉大括号。我也不确定$fh 应该是什么,因为你再也不会使用它了。

    您似乎对 Perl 的语法感到困惑。你是如何学习 Perl 的?

    【讨论】:

      【解决方案2】:

      您可能对文件名$file 和文件句柄$fh 感到困惑

      尝试将前三行更改为

      my $file= "words.txt";
      if (! -e $file) {
        my $fh = *STDIN;
      } else {
        open my $fh, '<', $file;
      }
      

      $fn 中似乎有错字。不应该是$fh吗?

      【讨论】:

        【解决方案3】:

        Perl 总是在条件句后需要大括号:

        你写道:

        if (! -e "$fh") $fh="STDIN";
        

        你应该写:

        if (! -e "$fh") { $fh="STDIN"; }
        

        或者:

        $fh = "STDIN" if ! -e "$fh";
        

        这些在语法上是正确的。不过,代码在语义上被分割成碎片。要打开文件,请使用:

        open my $fh, '<', $fn or die "Failed to open $fn";
        

        并且始终使用use strict;use warnings;。 Perl 专家使用它们来确保他们没有犯愚蠢的错误。新手也应该​​这样做。

        【讨论】:

          【解决方案4】:

          您对open 的理解不正确。将它与三参数调用一起使用的现代方式通常是:

          open my $fh, '<', <file name> or die $!;
          

          您指定一个新的文件句柄对象作为第一个参数,而不是文件名。您也不需要打开文件来检查它是否存在。因此,与其这样做,不如按照以下方式做一些事情:

          my $file = 'words.txt';
          if (! -e $file) {
            print "$file does not exist\n";
          }
          else {
           # open your file here and remember to close it
          }
          

          如果STDIN不存在,则只需使用特殊的菱形运算符&lt;&gt;STDIN进行操作。

          【讨论】:

            猜你喜欢
            • 2017-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多