in reply to Re: Calling func named in string
in thread Calling func named in string

Strictly speaking, if you get the syntax right there is no need for no strict 'refs';. See choroba's reply above and your updated test code below.

use strict; use warnings; my %JumpTbl = (TestSub1 => \&TestSub1, TestSub2 => \&TestSub2); my @FuncList = values %JumpTbl; $JumpTbl{'TestSub2'}(); $FuncList[0](); sub TestSub1 { print "TestSub1\n"; } sub TestSub2 { print "TestSub2\n"; }
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^3: Calling func named in string
by MikeL (Acolyte) on Dec 16, 2024 at 19:29 UTC

    There is a difference here...

    My goal was to type the list of names once, as it's fairly long (about 50). This is for both ease of typing, and for clarity of code.

    Your solution requires the redundant "thing => thing", whereas what I arrived at is simply a list of "things".

    I agree that it's a Good Thing to not turn off strict, but I'm willing to accept that in a very localized area, for this one line of code, in order to make this happen.

    P.S. Better solution arrived at above https://www.perlmonks.org/?node_id=11163205
      My goal was to type the list of names once

      Oh, well, in that case, how about not hand populating the list at all? Consider:

      use strict; use warnings; my @names = sort grep {/^TestSub/} keys %main::; my @FuncList = map {$main::{$_}} @names; $main::{TestSub2}(); $FuncList[0](); sub TestSub1 { print "TestSub1\n"; } sub TestSub2 { print "TestSub2\n"; }

      That depends on having a searchable pattern for your sub names, but means you don't have to maintain the list at all. Another hundred subs to add? Just add them to the code and run off grinning!

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond