Others pointed out the mistakes with the match. I shall talk further improvements. Here's how I would do it:
- I always use strict and use diagnostics so that Perl points out any dumb mistakes I make.
- Instead of traditional filehandles (CINGULAR) I use a scalar variable ($fh). It does not matter in this small program, but in larger I can take advantage of limiting the scope of the variable so that it doesn't unnecessarily pollute the namespace.
- I tell open to open the file for reading only with the <. Leaving it off means open for read/write, which can be dangerous if overlooked.
- The idiom is open or die instead of the variant with the logical operator || which requires lots of parentheses because it has such a high operator precedence.
- This is probably the most important hint: reading the whole file into an array to process it does not scale well. Once your file gets bigger than your RAM, the operating system must page out to disk and the program will become dog slow. A better approach is to read it line for line and process immediately.
use strict;
use diagnostics;
open my $fh, "<c:/documents and Settings/david price/my documents/cing
+ular.txt" or die "cannot open for reading: $!";
my $matches;
while (<$fh>) {
$matches++ if /9432$/;
last if $. == 100;
# skip to end of while once we have reached line 100
# $. is a built-in variable, see perlvar in the docs
};
close $fh;
print "Found $matches matches.\n";