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";
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.