in reply to Invoking a string reference to a anonymous subroutine

It seems like you're wanting a symbolic reference to refer to a lexical scalar (a my variable), which it can't directly. If, instead of 'my' you were using 'our', you could use the symbolic reference:

perl -E 'our $p = sub { 1 }; my $q = "p"; say $$q->();'

...but then your 'our' variable is a package global, and you're mucking around in the symbol table, which may be counterindicated for maintainability.

Couldn't this problem be solved with real refs and a hash table used as a dispatch table?

perl -E 'my %dispatch = ( p => sub { 1 } ); my $q = "p"; say $dispatch +{$q}->();'

Dave

Replies are listed 'Best First'.
Re^2: Invoking a string reference to a anonymous subroutine
by LanX (Saint) on Jan 14, 2014 at 20:32 UTC
    Hi Dave

    > It seems like you're wanting a symbolic reference to refer to a lexical scalar (a my variable), which it can't directly.

    indeed... from perlref

    Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren’t in a symbol table, and thus are invisible to this mechanism.

    It never occurred to me, thanks for pointing it out! =)

    Cheers Rolf

    ( addicted to the Perl Programming Language)