in reply to BWTDI: Better Way To Do It?
sub grab { my $class = shift; my $dice = shift; my $self = ref($class) || $class; unless ($dice =~ m/^(\d+)[Dd](\d+)([Ss])?$/ ) { croak "Invalid dice format to $self->grab: $dice"; } #$1 - Quantity #$2 - Type #$3 - Face my @dice = map { Die->get( $2, $3 ? 1 : 0 ) } 1..$1; return bless { dice => \@dice }, $self; }
Here's a summary of what I did:
I changed the code to be more in-line, as there is no need for a logic branch if the regex fails to return a match. Inside the croak command, I figured it was better to report back the passed in $dice, rather than $!, which is generaly set by system-level errors.
The regex was optimized. The /i modifier wasn't necessary because you were wanting to match d and D, using a character class is faster anyhow, as in: [Dd]. Same with the [Ss] on the end, which was made an optional match, rather than use the (.*) or (.*s). The Mastering Regex book cautions against using the /i when a character class will do just as well.
Instead of creating temporary variables, I used the $1, $2, $3 variables directly. Of course, I compensated for the loss in readability, by using comments =).
I could have pushed onto an array inside a loop, but map was used and the values were copied directly onto the array. I benchmarked using for, foreach and map, with map coming out as a winner in my tests. The others won when I experimented with making $1 equal to 10000 or so, but this will most likely not get this high, in the real-world.
Also, you'll notice that $3 ? 1 : 0 was used, it's not possible to do something like $3 &&= 1, since $3 is a read-only variable.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: BWTDI: And the winner is dkubb
by coreolyn (Parson) on Jan 15, 2001 at 21:12 UTC |