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
-
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.
|