#!/usr/bin/perl 
######################################################################
# fortune.pl
######################################################################
# Perl Power! - Michael Schilli 1998
######################################################################

######################################################################
  package Fortune;              # persistent class
######################################################################

use Persistent;
@ISA = qw(Persistent);          # inheritance

######################################################################
sub new {                       # constructor
######################################################################
    my $class = shift;
    my $self = {};
    bless($self, $class);

    $self->{'aphorisms'} = [];  # reference to empty
                                # fortune list
    return $self;
}

######################################################################
sub getany {                    # fetch fortune
######################################################################
    my $self = shift;
                                # random list index
    my $index = rand() * ($#{$self->{'aphorisms'}} + 1);
                                # extract element
    splice(@{$self->{'aphorisms'}}, $index, 1);
} 

######################################################################
sub add {                       # add fortune
######################################################################
    my $self = shift;
                                # append list to list
    push(@{$self->{'aphorisms'}}, @_);
} 

######################################################################
  package main;                 # main program
######################################################################

srand(time);                    # initialize random generator
                                # (no longer needed since perl 5.004)
my $datafile = "fortune.data";  # file for 
                                # persistent data
my $text;

my $fortune = Fortune->new();   # create persistent object 

if(! $fortune->load($datafile) ||    # load data from file
   ! ($text = $fortune->getany())) { # all fortunes used ?

   $fortune->add(               # reinitialization
    "The trouble with troubleshooting is that the trouble shoots back",
    "If something can go wrong, it will go wrong",
    "Long live Fortran!",
    "True programmers do not fear GOTOs");

   $text = $fortune->getany(); # fetch fortune
}

print "$text\n";                # output fortune

$fortune->store("$datafile");   # store modified object

