Having been a long-time gamer, and wanting to stretch my brain around IMPORTING AUTOLOADED FUNCTIONS, I came up with this little package.

package Games::Dice; use warnings; use strict; use vars '$AUTOLOAD'; sub AUTOLOAD { if ( $AUTOLOAD =~ /^.*::(\d+)[Dd](\d+)/ ) { buildsub($AUTOLOAD,$1,$2); goto &$AUTOLOAD; } } sub buildsub { my ($name,$rolls,$die) = @_; my $sub = <<END_SUB; sub $name { my \$result = $rolls; for( my \$i = 0; \$i < $rolls; \$i++ ) { \$result += int(rand($die)); } return \$result; } END_SUB eval $sub; die "Oops, dropped a die" if ($@); } sub import { no strict 'refs'; my $pkg = shift; my $caller = caller(0); for my $dice (@_) { if ($dice =~ /(\d+)[Dd](\d+)/) { buildsub("$pkg\::$dice",$1,$2); *{"$caller\::$dice"} = \&{"$pkg\::$dice"}; } } } 1; # Example use package main; use Games::Dice ( '3d6' ); my %rolls; for (1..1000) { my $roll = main::3d6; # The main:: is required because??? $rolls{$roll}++; } for (sort {$a<=>$b} keys %rolls) { print "$_ => $rolls{$_}\n"; }

In reply to Perlish dice for gamers (oh, and importing autoloaded functions) by Solo

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.