Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How do I call a sub using a variable as its name, objectively

by choroba (Cardinal)
on Oct 28, 2024 at 19:20 UTC ( [id://11162456]=note: print w/replies, xml ) Need Help??


in reply to How do I call a sub using a variable as its name, objectively

It's in fact much easier. Use a variable to keep the method name:
#!/usr/bin/perl use warnings; use strict; { package My; sub new { bless {}, shift } sub show { my ($self, $name) = @_; print "Hello $name!\n" } } my $A = 'My'->new; my $method = shift; $A->$method(@ARGV);

Using it:

$ 1.pl show World Hello World!

Otherwise, you need to do a reference/dereference trick:

$A->${\ $ARGV[0] }(@ARGV[1 .. $#ARGV]);

Update: Fixed arguments for the second example. Thaks etj.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: How do I call a sub using a variable as its name, objectively
by etj (Priest) on Oct 29, 2024 at 14:48 UTC
    To be exactly equivalent, that last one would need to be: $A->${\ $ARGV[0] }(@ARGV[1..$#ARGV]);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2025-06-16 04:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.