Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

lima1's scratchpad

by lima1 (Curate)
on Jul 25, 2007 at 18:27 UTC ( #628757=scratchpad: print w/ replies, xml ) Need Help??


When 100% Code Coverage Backfires
PBP's .perltidyrc file, was Re: Perl Best Practices
last hour of cb

Title: How do I skip the first $n lines of a file efficiently?

Question: Suppose I want to read a file but I'm not interested in the first $n lines. What's the best way of skipping these first $n lines? Answer: To accomplish this task, one often sees code like this:

my $line_id = 0; LINE: while (my $line = <$IN>) { $line_id++; next LINE if $line_id < $n; # now parse the interesting part of the file ... }
The problem with this approach is that the test is performed on every single line of the file. Which is not necessary as we can do the skipping before the main while loop. The probably shortest and most efficient way to do that is:
{ local $. = 0; do {} while ($. < $n && <$IN>); } while (my $line = <$IN>) { ... }
$. is the line counter of the current file handle. See perlvar.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2014-12-25 10:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls