Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Sub ref from string without eval

by kennethk (Abbot)
on Apr 02, 2012 at 14:51 UTC ( [id://963028]=note: print w/replies, xml ) Need Help??


in reply to Sub ref from string without eval

I suspect this is an XY Problem, but you can do this using Symbolic references. This will not work with strict refs in place (you do use strict, right?), so your code might look like
my $x = 'Foo'; my $sub_ref = do { no strict 'refs'; \&{$x}; };
so your code might look like
my $x = 'Foo'; my $sub_ref = \&{$x};
Update: It appears my $sub_ref = \&{'Foo'}; passes strict when &{'Foo'}; does not. Huh?

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Sub ref from string without eval
by moritz (Cardinal) on Apr 02, 2012 at 15:01 UTC
    \&{$x} works perfectly fine with strict refs. It is only implicit usage of strings as references that is prohibted by strict refs. If you go to the length of writing \&{ ... }, perl assumes a symbolic reference is indeed what you want.
    use strict; use warnings; use 5.010; sub Foo { 'in sub Foo' } my $x = 'Foo'; my $sub_ref = \&{$x}; say $sub_ref->(); __END__ in sub Foo

      It is only implicit usage of strings as references that is prohibted by strict refs.

      Nope.

      $ perl -e'use strict; my $x = "foo"; \${ $x }' Can't use string ("foo") as a SCALAR ref while "strict refs" in use at + -e line 1. $ perl -e'use strict; \${ "foo" }' Can't use string ("foo") as a SCALAR ref while "strict refs" in use at + -e line 1.

      \&{ ... } is clearly an exception.

Re^2: Sub ref from string without eval
by kejohm (Hermit) on Apr 02, 2012 at 22:46 UTC

    To quote strict:

    There is one exception to this rule:

    $bar = \&{'foo'}; &$bar;

    is allowed so that goto &$AUTOLOAD would not break under stricture.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://963028]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-24 02:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found