in reply to variable subroutine call
In a word: yup.
#!/usr/bin/perl use strict; use warnings; sub say_whoops { print "whoops\n"; } my %functions = ( 'hi' => sub {print "hi\n";}, 'bye' => sub {print "bye\n";}, 'whoops' => \&say_whoops, ); foreach my $key ( keys %functions ) { $functions{$key}(); }
The "hi" and "bye" are anonymous subroutines whereas whoops is executing via a reference to say_whoops(). I've stored the references in a hash simply because it's quick and easy though there are other ways. You can even pass them arguments! Take a look at perlsub for all the specifics.
HOWEVER, it's exceedingly dangerous to take arguments from STDIN to run a routine unless ya know where they're coming from. Potential security hazard. Striken as per shmem's comment. Guess I'm a worry wart really.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: variable subroutine call
by shmem (Chancellor) on Dec 12, 2007 at 01:27 UTC | |
by meraxes (Friar) on Dec 12, 2007 at 01:33 UTC | |
by shmem (Chancellor) on Dec 12, 2007 at 01:40 UTC | |
by meraxes (Friar) on Dec 12, 2007 at 01:49 UTC | |
by wfsp (Abbot) on Dec 12, 2007 at 08:46 UTC |