#!/usr/bin/perl
=begin metadata
Name: random
Description: display lines at random, or exit with a random value
Author: Abigail, perlpowertools@abigail.be
License: perl
=end metadata
=cut
use strict;
use Getopt::Std;
my ($VERSION) = '1.2';
my $warnings = 0;
END {
close STDOUT || die "$0: can't close stdout: $!\n";
$? = 1 if $? == 255; # from die
}
# Print a usuage message on a unknown option.
# Requires my patch to Getopt::Std of 25 Feb 1999.
$SIG {__WARN__} = sub {
if (substr ($_ [0], 0, 14) eq "Unknown option") {die "Usage"};
require File::Basename;
$0 = File::Basename::basename ($0);
$warnings = 1;
warn "$0: @_";
};
$SIG {__DIE__} = sub {
require File::Basename;
$0 = File::Basename::basename ($0);
if (substr ($_ [0], 0, 5) eq "Usage") {
die <<EOF;
$0 (Perl game utils) $VERSION
$0 [-er] [denominator]
EOF
}
die "$0: @_";
};
# Get the options.
getopts ('er', \my %options);
die "Usage" if @ARGV > 1;
my $denominator = @ARGV ? shift : 2;
die "Usage" if $denominator =~ /\D/ || $denominator == 0;
exit int rand $denominator if exists $options {e};
$| = 1 if exists $options {r};
my $frac = 1 / $denominator;
while (<>) {print if $frac >= rand;}
exit $warnings;
__END__
=pod
=head1 NAME
random - display lines at random, or exit with a random value
=head1 SYNOPSIS
random [-er] [denominator]
=head1 DESCRIPTION
I<random> reads line from standard input, and displays each line on
standard output which chance 1 / I<denominator>. If the I<-e> option
is given, I<random> exits with a value randomly choosen from C<0> to
C<denominator - 1> inclusive. If no I<denominator> is given, 2 is used.
=head2 OPTIONS
I<random> accepts the following options:
=over 4
=item -e
Exit with a value randomly choosen from C<0> to C<denominator - 1> inclusive.
Do not read input, or display output.
=item -r
Use unbuffered output.
=back
=head1 ENVIRONMENT
The working of I<random> is not influenced by any environment variables.
=head1 BUGS
There are no known bugs in I<random>.
=head1 AUTHOR
The Perl implementation of I<random> was written by Abigail, I<perlpowertools@abigail.be>.
=head1 COPYRIGHT and LICENSE
This program is copyright by Abigail 1999.
This program is free and open software. You may use, copy, modify, distribute
and sell this program (and any modified variants) in any way you wish,
provided you do not restrict others to do the same.
=cut