#!/usr/bin/perl =head1 NAME randomline -- pick a single randline fro ma file (ignore comment lines) =head1 SYNOPSIS randomline [option] filelist... > random_file Options: -v output line to standard error channel as well -l print line number of pick (for debuging) -e print element number of pick (for debuging) =head1 DESCRIPTION This program is based on a program in the Perl (Camel) Book, page 246, which does a single pass on a file and does NOT read the file into an array. It is based on the proability at the current line would be picked IF it is the last line of the file. It all works out evenly. Any comment lines in the input are ignored. If no comments are present in the file the the line number (-l) and element number (-e) will be the same. Comments are either 1/ A line starting with `!' which doesn't interfer with cpp 2/ or from the character # to the end of line =head1 AUTHOR Anthony Thyssen =cut sub Usage { use Pod::Usage; pod2usage("@_"); exit 10; } ARGUMENT: # Multi-switch option handling while( @ARGV && $ARGV[0] =~ s/^-(?=.)// ) { $_ = shift; { m/^$/ && do { next }; # next argument m/^-$/ && do { last }; # End of options m/^\?/ && do { Usage }; # Usage Help s/^v// && do { $verbose++; redo }; # output to stderr too s/^l// && do { $out_linenum++; redo }; # line number of pick (debug) s/^e// && do { $out_element++; redo }; # element number of pick (debug) Usage( "Unknown Option \"-$_\"\n" ); } continue { next ARGUMENT }; last ARGUMENT; } # ----------------------------------------- # removed as first login afetr a reboot seemed to produce the same 'background' #srand( time ^ $$ ); # perl now randomises better on its own $line = 0; # line number -- determine posibility of selecting this line while(<>) { next if /^!/; # skip the ! comments (for cpp) s/#.*$//; # remove any comment ( # to end of line ) next unless /\S/; # skip any resulting blank lines $num++; $pick = $_, $l=$., $n=$num if rand( $num ) < 1; # element be picked if it was the last line } $pick =~ s/\s*$//; # remove any extra spaces at end of line print $pick, "\n"; print STDERR $pick, "\n" if $verbose; print STDERR "$l\n" if $out_linenum; print STDERR "$n\n" if $out_element;