4

私は初めて 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
4

4 に答える 4

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 に答える
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 に答える