I'd also recommend Tie::File or a database.

However, if you really prefer to use a flat file you could try somehing like the following. It selects a random line in the file and does an in-place edit so that the line is effectively removed.

#!/usr/bin/perl -w use strict; my $passwords = 'passwords'; # It would be better to cache the $count value in a separate file my $count = `wc -l $passwords`; # Bail out if wc failed exit if $?; # Get the line count $count = (split ' ', $count)[0]; # Bail out if the file is empty die "No passwords in $passwords\n" unless $count; my $key = 1 + int rand $count; my $password; # Localised in-place edit { local $^I = ''; local @ARGV = $passwords; while (<>) { if ($. == $key) { chomp; $password = $_; } else { print; } } } print $password, "\n"; __END__
However, if the selection doesn't have to be random it would be more efficient to read a record from the end and then truncate the file as shown below.

--
John.


In reply to Re: popping or shifting a line off a file by jmcnamara
in thread popping or shifting a line off a file by nmerriweather

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.