in reply to popping or shifting a line off a file


If you don't have to select the lines randomly then you could do something like this:
#!/usr/bin/perl -w use strict; my $passwords = 'passwords'; my $rec_size = 9; my $password; open PASS, "+<$passwords" or die "Error message here $!"; # Seek from end of file seek PASS, -$rec_size, 2; # Store the position of the last seek my $last = tell PASS; # Read the password but not the newline read PASS, $password, $rec_size -1; # Remove the record just read truncate PASS, $last; close PASS; print $password, "\n"; __END__

This method will be significantly faster than the method shown above.

--
John.

Replies are listed 'Best First'.
Re: Re: popping or shifting a line off a file
by nmerriweather (Friar) on Jul 29, 2002 at 20:36 UTC
    i finally ended up with something similar...
    print &popline("passcodes.txt",10,7); sub popline { my ($file, $lineswanted, $linelength) = @_; open DATA, "+< $file"; my @fileinfo = stat DATA; my %records = (); $records{filesize} = $fileinfo[7]; $records{wanted_bytes} = $lineswanted * $linelength; $records{readpoint} = $records{filesize} - $records{wanted_byt +es}; # seek (DATA, -$records{wanted_bytes},2); # reads from the end + of file, readpoint computation not necessary seek (DATA, $records{readpoint},0); # reads from beginn +ing, used b/c readpoint computation needed for truncate my @lines = <DATA>; truncate(DATA,$records{readpoint}); return @lines; }
    i'll add in flocking etc tonight.
    short of filling up a database w/20k possible keys + status tags, what i did was create a flat.txt of possible keys. this function is for 'activating' a key -- 50-100 will be pulled off the file, inserted into a db with a status flag (active/used), and merged w/documentation is this the most secure method? probably not. but if someone is going to hack my machine and grab the file -- well, i'm just going to assume that they're talented enough to hack into mysql and alter the db as they see fit.