There's nothing earth-shattering here; just a Perldoodle.
There are a lot of dice modules already on CPAN. This snippet isn't a replacement for those. It just offers a different twist. You can define the faces of the die. That allows for traditional six sided numeric-faced dice, or alphabet-faced dice, or even, magic-eight-ball style dice.
The object constructor (new) takes an array-ref (or an anonymous array) as its argument. That anon-array must enumerate the faces of the die.
The CPAN dice modules focus on simple numeric dice rolls, as well as "D&D notation". This package just focuses on custom dice faces.
See the examples below:
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";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.