Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Loading a part of the file to array using Tie::File (updated)

by haukex (Archbishop)
on Nov 21, 2017 at 14:56 UTC ( [id://1203889]=note: print w/replies, xml ) Need Help??


in reply to Loading a part of the file to array using Tie::File

Tie::File does not read the entire file into memory, it only caches a certain number of lines. See its memory option for controlling the cache size.

use Tie::File; tie my @array, 'Tie::File', $filename or die $!; my $l = 9; # line 10 while (defined( my $line = $array[$l] )) { print "<$line>\n"; } continue { $l++ }

Note that I am not accessing the size of the array with $#array, or @array in scalar context, as this would require the module to scan the entire file once (but again, not load all of it into memory at once).

If you are interested in reading only a certain number of lines from the end of a file, perhaps File::ReadBackwards would be of interest.

Update: I should also say that if you're only interested in reading the file sequentially, not doing random access or modifying it, Tie::File doesn't give you a great advantage as it introduces extra overhead, and a simple while(<>) loop like glasswalk3r showed would likely be much more efficient. You can use $. to keep track of the current line number.

Update 2: Here's one way to skip N lines (not based on the current line number):

open my $fh, '<', $filename or die "$filename: $!"; scalar <$fh> for 1..9; # skip 9 lines while (<$fh>) { chomp; print "<$_>\n"; } close $fh;

Update 3 (last one, I think ;-) ): To operate only on certain ranges of lines based on their line number, you can use Perl's Range Operators, for example next if 5 .. 10; will skip lines 5 through 10. Note this is a different form of the operator used above. Also minor edits for clarity.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-18 00:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found