package Die; use strict; use warnings; sub new { my ( $proto, $faces ) = @_; my $class = ref( $proto ) || $proto; my $self = {}; unless ( defined( $faces ) && ref( $faces ) =~ m/ARRAY/ ) { die "Must initialize Die with an array ref of faces.\n"; } # Make copy of @$faces so that faces can't be # corrupted from outside the package. $self->{Faces} = [@{$faces}]; bless $self, $class; return $self; } sub roll { my $self = shift; return $self->{Faces}[ rand( @{ $self->{Faces} } ) ]; } package main; use strict; use warnings; my $six_sided = Die->new( [1..6] ); my $eight_sided = Die->new( [1..8] ); my $alpha_faced = Die->new( ['A'..'Z'] ); my $eight_ball = Die->new( [ "Yes", "I'll never tell", "Perhaps", "No", "Ask Again Later", "Outlook positive", "Don't bet on it", "Of course" ] ); foreach ( $six_sided, $eight_sided, $alpha_faced, $eight_ball ) { print $_->roll(), "\n"; }