Reputation: 87
I am working with different subroutines of a Perl script. It is possible to call a single subroutine from the Perl script via the Unix shell like:
simplified examples:
perl automated_mailing.pl inf
then the function inform_user
from automated_mailing.pl
gets called.
This is realized through a dispatch table:
my %functions = (
inf=> \&inform_user,
);
inform_user
looks like
sub inform_user{
print "inform user: Angelo";
...some other stuff...
}
The question now is, how to replace "Angelo" with a variable and call it from shell like:
sub inform_user{
my ($to)=@_;
print "inform user: $to";
}
This call does not work:
perl automated_mailing.pl inf("Brian")
How is this be done correctly?
Upvotes: 3
Views: 313
Reputation: 87
With the given hint i reached exactly what i wanted. the programm now looks like:
use warnings;
use strict;
sub inform_user{
my @to = @ARGV;
print "inform user: $to[0]";
}
my %functions = (
inform_user=> \&inform_user,
);
my $function = shift;
if (exists $functions{$function}) {
$functions{$function}->();
} else {
die "There is no function called $function available\n";
}
and the output is:
>> perl automated_mailing.pl inf Brian
>> inform user: Brian
Upvotes: 0
Reputation: 69244
You need to pass the arguments as separate command-line parameters:
perl automated_mailing.pl inf Brian
You need to pass the command-line parameters onto the subroutine that you call:
my ($func, @args) = @ARGV;
# And then later...
if (exists $functions{$func}) {
$functions{$func}->(@args);
} else {
die "$func is not a recognised function\n";
}
You haven't shown the code for the actual use of the dispatch table - so my second point is a bit of guesswork.
Upvotes: 4