This code snippet contains a bug free(R) expression allowing you to parse D20 notation dice, so you can parse strings like 3D6,3D6+4 and 3D6+4x1000 obtaining as result (for 3D6+4x1000):
$dtime = 3
$dface = 6
$addfact = 4
$mulfact = 1000
The snippet set also right default value is a field is missing, so you can use returned value directly for calculation
#!/usr/bin/perl -w
use strict;
my @sample=("3D6+","3D6","3D6+4","3D6+4x1000");
##############################THE BIG, THE ONE
my $rexp='^([1-9][0-9]*)[Dd]([1-9][0-9]*)(\+([1-9][0-9]*)(x([1-9][0-9]
+*))?)?$';
my ($dtime,$dface,$foo,$addfact,$bar,$mulfact);
foreach (@sample)
{
if (/$rexp/)
{
map{$_=0 if !defined($_)}($dtime,$dface,$foo,$addfact,$bar)=($
+1,$2,$3,$4,$5);
$mulfact=(!defined($6))?1:$6;
print "$_ is $dtime dices with $dface faces plus $addfact all
+mult by $mulfact\n";
}
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.