4

我是第一次学习 PERL,我正在尝试完全复制本文档第四页上的简单 Perl 脚本:

这是我的代码:

# example.pl, introductory example

# comments begin with the sharp sign

# open the file whose name is given in the first argument on the command 
# line, assigning to a file handle INFILE (it is customary to choose
# all-caps names for file handles in Perl); file handles do not have any
# prefixing punctuation
open(INFILE,$ARGV[0]);

# names of scalar variables must begin with $
$line_count - 0;
$word_count - 0;

# <> construct means read one line; undefined response signals EOF
while ($line - <INFILE>) {
    $line_count++;
    # break $line into an array of tokens separated by " ", using split()
    # (array names must begin with @)
    @words_on_this_line - split(" ",$line);

    # scalar() gives the length of an array
    $word_count += scalar(@words_on_this_line);
}

print "the file contains ", $line_count, "lines and ", $word_count, " words\n";

这是我的文本文件:

This is a test file for the example code.
The code is written in Perl.
It counts the amount of lines 
and the amount of words.
This is the end of the text file that will
be run
on the example
code.

我没有得到正确的输出,我不知道为什么。我的输出是:

C:\Users\KP\Desktop\test>perl example.pl test.txt
the file contains lines and  words
4

4 回答 4

6

由于某种原因,您所有的“=”运算符似乎都是“-”

$line_count - 0;
$word_count - 0;
...
while ($line - <INFILE>) {
...
@words_on_this_line - split(" ",$line);

我建议使用“我的”来声明你的变量,然后“使用严格”和“使用警告”来帮助你检测这样的错别字:

目前:

$i -1;

/tmp/test.pl -- 无输出

当您添加严格和警告时:

use strict;
use warnings;

$i -1;

/tmp/test.pl 全局符号“$i”在 /tmp/test.pl 第 4 行需要明确的包名称。/tmp/test.pl 的执行由于编译错误而中止。

当您添加“我的”来声明它时:

vim /tmp/test.pl
use strict;
use warnings;

my $i -1;

/tmp/test.pl 在 /tmp/test.pl 第 4 行的 void 上下文中无用地使用减法 (-)。在 /tmp/test.pl 第 4 行的减法 (-) 中使用未初始化的值。

最后用“=”代替“-”错字——这就是正确的声明和初始化的样子:

use strict;
use warnings;

my $i = 1;
于 2013-05-21T19:55:37.947 回答
3

您必须在代码中的多个句子中更改 - by = 。此外,我还包含了一些与获得更现代的 perl 代码相关的更改(use strict这是必须的)

use strict;
use warnings;

open my $INFILE, '<', $ARGV[0] or die $!;

# names of scalar variables must begin with $
my $line_count = 0;
my $word_count = 0;

# <> construct means read one line; undefined response signals EOF
while( my $line = <$INFILE> ) {
    $line_count++;
    # break $line into an array of tokens separated by " ", using split()
    # (array names must begin with @)
    my @words_on_this_line = split / /,$line;

    # scalar() gives the length of an array
    $word_count += scalar(@words_on_this_line);
}

print "the file contains ", $line_count, "lines and ", $word_count, " words\n";

close $INFILE;
于 2013-05-21T19:57:28.973 回答
2

代替while ($line - <INFILE>) {

while ($line = <INFILE>) {

于 2013-05-21T19:50:32.833 回答
1

字数统计部分可以变得更简单(也更有效)。如果在标量上下文中调用,Split 返回数字元素。

代替

my @words_on_this_line = split / /,$line;
$word_count += scalar(@words_on_this_line);

$word_count += split / /,$line;
于 2013-05-21T20:43:01.803 回答