Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A couple of people have mentioned a dispatch table. There are two things and it's nice to keep them apart sometimes. There's the list of possible things that could happen, and the thing that makes them happen. If you couple the two, you're stuck with your solution. If you keep them separate, you have more flexibility later.</p> <p>The dispatch table specifies the behavior as data instead of program structure. Here's two different ways to do it. With your example you have integers and something like that might use an array to store things. The hash example is the same idea but looks up the behavior slightly differently.</p> <p>Also notice that I factor out the <code>print</code>. When you have repeated code like that, try to move the repeated stuff up a level.</p> <pre><code>use v5.10; foreach my $factor ( map { int rand 5 } 0 .. 9 ) { say get_age_array( $factor ); } my @animals = qw( cat dog bird frog ); foreach my $factor ( map { $animals[ rand @animals ] } 0 .. 9 ) { say get_age_hash( $factor ); } sub get_age_array { my $factor = shift; state $dispatch = [ sub { 'Nothing!' }, # index 0 sub { "Calling 1" }, sub { 1 + 1 }, sub { "Called 3" }, sub { time }, ]; return unless int $factor &lt;= $#$dispatch; $dispatch-&gt;[$factor]-&gt;(); } sub get_age_hash { my $factor = shift; state $dispatch = { 'cat' =&gt; sub { "Called cat" }, 'dog' =&gt; sub { "Calling 1" }, 'bird' =&gt; sub { "Calling 2, with extra" }, }; return unless exists $dispatch-&gt;{$factor}; $dispatch-&gt;{$factor}-&gt;(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload