Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: help manipulating data in an array.

by Anonymous Monk
on Nov 12, 2004 at 13:21 UTC ( [id://407348]=note: print w/replies, xml ) Need Help??


in reply to help manipulating data in an array.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://407348]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-25 05:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found