Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your friend is <a href="http://perldoc.perl.org/UNIVERSAL.html" rel="nofollow noreferrer"><code>can</code></a>. It returns a reference to the subroutine if it exists, null otherwise. It even does it correctly walking up the OO chain.</p> <pre><code>$self-&gt;{tests} = [ $self-&gt;can('_sub1'), $self-&gt;can('_sub2'), ]; # later for $tn (0..$#{$self-&gt;{tests}}) { ok defined $self-&gt;{tests}[$tn], "Function $tn is available."; } # and later my $ref = $self-&gt;{tests}[0]; $self-&gt;$ref(@args1); $ref = $self-&gt;{tests}[1]; $self-&gt;$ref(@args2); </code></pre> <p>Or, thanks to <a href="https://stackoverflow.com/questions/2804109/how-do-i-use-an-index-in-an-array-reference-as-a-method-reference-in-perl">this</a> question (which happens to be a variation of <a href="https://stackoverflow.com/questions/1836178/how-do-i-call-a-function-name-that-is-stored-in-a-hash-in-perl">this</a> question), you can call it directly:</p> <pre><code>$self-&gt;${\$self-&gt;{tests}[0]}(@args1); $self-&gt;${\$self-&gt;{tests}[1]}(@args1); </code></pre> <p>Note that the <code>\</code> gives us a reference to a the subref, which then gets dereferenced by the <code>${}</code> after <code>$self-&gt;</code>. Whew!</p> <p>To solve the timeliness issue brain d foy mentions, an alternative would be to simply make the {test} a subroutine itself, that returns a ref, and then you could get it at exactly the time you need it: </p> <pre><code>sub tests { return [ $self-&gt;can('_sub1'), $self-&gt;can('_sub2') ]; } </code></pre> <p>and then use it:</p> <pre><code>for $tn (0..$#{$self-&gt;tests()}) { ... } </code></pre> <p>Of course, if you have to iterate over the refs anyway, you might as well just go straight for passing the reference out:</p> <pre><code>for my $ref (0..$#{$self-&gt;tests()}) { $self-&gt;$ref(@args); } </code></pre>
    singulars
    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. 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