Perl Script to Count Words/Lines

perlscripting

I'm learning PERL for the first time and I am attempting to replicate exactly the simple Perl script on page four of this document:

This is my code:

# 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";

and this is my text file:

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.

I'm not getting the right output and I'm not sure why. My output is:

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

Best Solution

For some reason all your "=" operators appear to be "-"

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

I'd recommend using "my" to declare your variables and then "use strict" and "use warnings" to help you detect such typos:

Currently:

$i -1;

/tmp/test.pl -- no output

When you add strict and warnings:

use strict;
use warnings;

$i -1;

/tmp/test.pl Global symbol "$i" requires explicit package name at /tmp/test.pl line 4. Execution of /tmp/test.pl aborted due to compilation errors.

When you add "my" to declare it:

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

my $i -1;

/tmp/test.pl Useless use of subtraction (-) in void context at /tmp/test.pl line 4. Use of uninitialized value in subtraction (-) at /tmp/test.pl line 4.

And finally with a "=" instead of the "-" typo -- this is what the correct declaration and initializatoin looks like:

use strict;
use warnings;

my $i = 1;