in reply to Calling func named in string

I'm answering my own question, I got it figured out - I was making this much harder than necessary. In the following, I included line 16 which calls outside of the "no strict 'refs'", causing an error, so as to show that "strict refs" is operating normally outside of the block. Also, if you only want to call out a sub by a number, you don't need the JumpTbl hash, that's only needed to call it out by name:

use strict; + use warnings; my @FuncList = qw(TestSub1 TestSub2); my %JumpTbl = map { $_ => $_ } @FuncList; { no strict 'refs'; $JumpTbl{'TestSub2'}(); $FuncList[0](); } $JumpTbl{'TestSub1'}(); exit; sub TestSub1 { print "TestSub1\n"; } sub TestSub2 { print "TestSub2\n"; }

Output:

TestSub2 TestSub1 Can't use string ("TestSub1") as a subroutine ref while "strict refs" +in use at ./triv.pl line 16.

Replies are listed 'Best First'.
Re^2: Calling func named in string
by GrandFather (Saint) on Dec 15, 2024 at 20:29 UTC

    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

      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