I think I may have found a way that could be more efficient:
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.


In reply to Re: BWTDI: Better Way To Do It? by dkubb
in thread BWTDI: Better Way To Do It? by coreolyn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.