Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^5: Function name in a variable, can't recall the concept (updated x2)

by AnomalousMonk (Archbishop)
on Apr 03, 2019 at 18:51 UTC ( [id://1232109]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Function name in a variable, can't recall the concept
in thread Function name in a variable, can't recall the concept

I'll stick to my assertion that asub can properly be deemed a "method" of main for | for the purposes of  -> invocation (although I have to agree that this terminology (update: and usage!) is a little bit perverse): it follows all the rules for class and object reference invocation. And  main::$x() can even be made to work (sorta) without strictures (which were invented (update: in part) to put a stop to this kind of madness) if the string variable is a package variable and syntax is as documented.

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub func { print qq{hey @_}; } my $symref = 'func'; our $symref = 'func'; ;; my $mainobj = bless []; dd $mainobj; ;; main->$symref('ho'); $mainobj->$symref('there'); ;; &$main::symref('nonny-nonny'); " bless([], "main") hey main ho hey main=ARRAY(0x157618c) there Can't use string ("func") as a subroutine ref while "strict refs" in u +se at -e line 1. c:\@Work\Perl\monks>perl -w -MData::Dump -le "sub func { print qq{hey @_}; } my $symref = 'func'; our $symref = 'func'; ;; my $mainobj = bless []; dd $mainobj; ;; main->$symref('ho'); $mainobj->$symref('there'); ;; &$main::symref('nonny-nonny'); " bless([], "main") hey main ho hey main=ARRAY(0x185614c) there hey nonny-nonny
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub func { print qq{hey @_}; } sub bonk { print qq{zot @_}; } ;; my $symref = 'func'; ;; use vars qw($symref); $main::symref = 'bonk'; ;; my $mainobj = bless []; dd $mainobj; ;; main -> $symref('ho'); 'main' -> $symref('hi'); my $mainstring = 'main'; $mainstring -> $symref('he'); $mainobj -> $symref('there'); ;; no strict 'refs'; &$main::symref('nonny-nonny'); " bless([], "main") hey main ho hey main hi hey main he hey main=ARRAY(0x37716c) there zot nonny-nonny
(And they're not anomalies, they are features!) Run under ActiveState 5.8.9.

Update 1: Changed example code to better illustrate difference between lexical and package variables.

Update 2: And BTW, this even works (under strictures!) with aliasing:

my $str = 'aaa'; for my $alias (main::, 'main', $mainstring, $mainobj) { $alias->$symref($str++); }


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-16 11:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found