# $userid already populated # first check cache open(CACHE, "; close CACHE; # now get the most recently cached line # as a line could be cached multiple times my @lines = grep{/$userid/}@cached; my $line = pop @lines || ''; # only look though the file if we have not cached the # data associated with $userid recently if (not $line) { open(FILE,"FILE.txt") or die "Oops $!"; while() { if(/$userid/o) { $line = $_; close FILE; last; # exit as soon as we find $userid; } } close FILE; } # do the stuff if ($line) { chomp $line; cache($line); my ($inv, $date, $amt)= split(/[|]/); #code to build hash. } else { warn "Can't find userid: $userid\n"; } sub cache { my $line = shift; open(CACHE, ">>cache.txt") or die "Oops unable to open cache to append: $!"; flock CACHE, LOCK_EX; print CACHE "$line\n"; close CACHE; } # to limit the cache size you will need to clean it up # from time to time say via a cron tab. this sub take # the desired maximum cache size as its argument sub clean_cache { my $max_length = shift; open(CACHE, "+; my $start = $#cache - $max_length; $start = 0 if $start < 0; seek CACHE, 0, 0; truncate CACHE, 0; print CACHE @cache[$start..$#cache]; close CACHE; }