繁体   English   中英

用于计算单词/行的Perl脚本

[英]Perl Script to Count Words/Lines

我是第一次学习PERL而且我试图在本文档的第4页上完全复制简单的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

出于某种原因,所有“=”运算符都显示为“ - ”

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

我建议使用“my”来声明你的变量然后“use strict”和“use warnings”来帮助你检测这样的错别字:

目前:

$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上下文中无用地使用减法( - )4。在/tmp/test.pl第4行的减法( - )中使用未初始化的值。

最后用“=”而不是“ - ”拼写错误 - 这就是正确的声明和initializatoin的样子:

use strict;
use warnings;

my $i = 1;

你必须在代码中用多个句子改变 - 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;

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

with while ($line = <INFILE>) {

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

更换

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

$word_count += split / /,$line;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM