scripting - Perl Script to Count Words/Lines -
i'm learning perl first time , attempting replicate simple perl script on page 4 of document:
this code:
# example.pl, introductory example # comments begin sharp sign # open file name given in first argument on command # line, assigning file handle infile (it customary choose # all-caps names file handles in perl); file handles not have # prefixing punctuation open(infile,$argv[0]); # names of scalar variables must begin $ $line_count - 0; $word_count - 0; # <> construct means read 1 line; undefined response signals eof while ($line - <infile>) { $line_count++; # break $line array of tokens separated " ", using split() # (array names must begin @) @words_on_this_line - split(" ",$line); # scalar() gives length of array $word_count += scalar(@words_on_this_line); } print "the file contains ", $line_count, "lines , ", $word_count, " words\n"; and text file:
this test file example code. code written in perl. counts amount of lines , amount of words. end of text file run on example code. i'm not getting right output , i'm not sure why. output is:
c:\users\kp\desktop\test>perl example.pl test.txt file contains lines , words
for reason "=" operators appear "-"
$line_count - 0; $word_count - 0; ... while ($line - <infile>) { ... @words_on_this_line - split(" ",$line); i'd recommend using "my" declare variables , "use strict" , "use warnings" detect such typos:
currently:
$i -1; /tmp/test.pl -- no output
when add strict , warnings:
use strict; use warnings; $i -1; /tmp/test.pl global symbol "$i" requires explicit package name @ /tmp/test.pl line 4. execution of /tmp/test.pl aborted due compilation errors.
when add "my" declare it:
vim /tmp/test.pl use strict; use warnings; $i -1; /tmp/test.pl useless use of subtraction (-) in void context @ /tmp/test.pl line 4. use of uninitialized value in subtraction (-) @ /tmp/test.pl line 4.
and "=" instead of "-" typo -- correct declaration , initializatoin looks like:
use strict; use warnings; $i = 1;
Comments
Post a Comment