Was thinking about how to improve this, and wondered if it
was possible to make ' d' a binary operator, e.g.
just write 3d6 in your Perl code and have the
d operator get passed 3 and 6 as parameters, but having
checked out overload and TheDamian's OO book I
think it can't be done.
I then wrote a version that overloaded strings, so you could type $x='3d6' but really I think that's not
that much more intuitive. So...
As I've played recently with TheDamian's Filter::Simple I wrote a helper module that allows you to write $x=3d6 in your script.
As always comments welcome...
package Dice::Simpler;
use strict; use warnings;
use Filter::Simple;
use Dice::Simple qw(roll);
our @ISA=qw(Exporter);
our @EXPORT=qw(roll);
FILTER_ONLY
code => sub {
s{((?:\btt\d+\s+)?(?:\d+|\b)d\d+)}
# note use of \b. We don't want to filter other expressions
# that ending in 'd' and a number
{roll('$1')}g;
}
__DATA__
=head1 NAME
Dice::Simpler - an even simpler interface to RPG style dice.
=head1 SYNOPSIS
use Dice::Simpler;
my $str= tt3 6d6; # best 3 of 6 6-sided dice
my $dex= 3d8; # 3 8-sided dice
my $cha= 4d4+1; # 4 4-sided dice + 1
print <<CHARACTER;
Your new character has:
Strength: $str
Dexterity: $dex
Charisma: $cha
===============
CHARACTER
print "You attack the Orc:\n";
if (3d6 < $str) {
print "You killed the Orc";
} else {
print "You hit the Orc but it glanced off his armour";
}
=head1 DESCRIPTION
Uses L<Dice::Simple> and the very funky L<Filter::Simple> to allow you
+ to use
the RPG style '3d6' syntax for dice rolling directly in Perl. See the
+
Dice::Simple documentation for more details.
=head1 AUTHOR, LICENSE
Version: 0.01 8th Dec 2001
Untested. No warranty implied.
May be distributed under the same terms as Perl itself.
(c) hakim@earthling.net
http://www.perlmonks.org /msg osfameron
=head1 BUGS
=over 4
=item 1
(OPEN 2001/12/8) '3d6' notation isn't filtered in quotelikes like
double quoted strings. But it *does* seem to be in <<heredocs. Not s
+ure why. B<Update:> but Damian Conway himself is aware of it, and it
+is on his looooong todo list, thanks!
=back
=cut
int(rand 6)+1;
Cheerio!
Osfameron
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|