swi*_*bhs 1 syntax perl scalar operator-keyword
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
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
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.
Run Code Online (Sandbox Code Playgroud)
请帮忙
在条件之后,Perl 总是需要在代码周围使用大括号:
你写了:
if (! -e "$fh") $fh="STDIN";
Run Code Online (Sandbox Code Playgroud)
你应该写:
if (! -e "$fh") { $fh="STDIN"; }
Run Code Online (Sandbox Code Playgroud)
要么:
$fh = "STDIN" if ! -e "$fh";
Run Code Online (Sandbox Code Playgroud)
这些在语法上是正确的.但是,代码在语义上被打成碎片.要打开文件,请使用:
open my $fh, '<', $fn or die "Failed to open $fn";
Run Code Online (Sandbox Code Playgroud)
并始终使用use strict;和use warnings;.Perl专家使用它们来确保它们没有犯下愚蠢的错误.新手也应该这样做.
| 归档时间: |
|
| 查看次数: |
320 次 |
| 最近记录: |