Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Loading file into memory

by monarch (Priest)
on Aug 05, 2008 at 18:32 UTC ( #702441=note: print w/replies, xml ) Need Help??

in reply to Loading file into memory

Another method: store a hash with the key being the name and the value being the position in the file of the desired record.

This will generally be slower when accessing records because the file itself must be interrogated, but it could potentially be faster as it minimises the risk of the file turning into swap memory (which is expensive to access at any rate).

Your specification was rather unclear, so for the purposes of example code I will assume that you want a record given an $id (e.g. "daamaya") and a $name (e.g. "Daniel R. Amaya"). So I will construct a hash of ids that point to a hash of names that point to a position in the file containing the desired record.


my %ids = (); my $curpos = 0; # position within the file while ( defined( my $line = <HANDLE> ) ) { # we want my ( $part_left, $part_right ) = split( /\s*,\s*/, $line ); my ( $id, $name ) = split( /:/, $part_left ); $ids{$id}->{$name} = $curpos; $curpos += length( $line ); } # later when we want to look up a record sub get_record( $ $ ) { my ( $id, $name ) = @_; # arguments my $filepos = $ids{$id}->{$name}; seek( HANDLE, $filepos, 0 ); my $line = <HANDLE>; my ( $part_left, $part_right ) = split( /\s*,\s*/, $line ); return( $part_right ); } # e.g. get_record( "daamaya", "Daniel R. Amaya" ); # process $line

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2016-10-21 13:33 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (289 votes). Check out past polls.