Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: reading the file using the line number

by ikegami (Patriarch)
on Nov 29, 2006 at 07:37 UTC ( [id://586633]=note: print w/replies, xml ) Need Help??


in reply to reading the file using the line number

Tie::File is simplest.

tie my @array, 'Tie::File', $file_name or die("Unable to open file \"$file_name\": $!\n"); print($array[$_]) for 6, 1003, 2965;

Tie::File can use a fair bit of memory (for its index, which is above and beyond what the memory argument limits), so you might want to write your own (faster, more memory efficient) solution.

my %lines_of_interest = map { $_ => 1 } 6, 1003, 2965; open my $fh, '<', $file_name or die("Unable to open file \"$file_name\": $!\n"); my $num_lines = keys %lines_of_interest; while (<$fh>) { if ($lines_of_interest{$.}) { print; last unless --$num_lines; } }

Update: Added Tie::File code.
Update: Added key counting to exit loop sooner.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2024-04-24 13:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found