#!/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.3';

my %options;
getopts('er', \%options) or usage();
my $denominator = shift;
$denominator = 2 unless defined $denominator;
usage() if @ARGV;
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 0;

sub usage {
    warn "usage: $0 [-er] [denominator]\n";
    exit 1;
}

__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

