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"; }

In reply to Custom-faced Dice by davido

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.