CUFP
Luca Benini
snippet
<div class="Description">This code snippet contains a bug free(R) expression allowing you to parse D20 notation dice, so you can parse strings like <I>3D6</I>,<I>3D6+4<I> and <I>3D6+4x1000</I> obtaining as result (for <I>3D6+4x1000</I>):<BR>
$dtime = 3 <BR>
$dface = 6 <BR>
$addfact = 4 <BR>
$mulfact = 1000 <BR>
The snippet set also right default value is a field is missing, so you can use returned value directly for calculation
</div>
<CODE>
#!/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";
}
}
</CODE>