3

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?

2 Answers 2

4
  1. You need to pass the arguments as separate command-line parameters:

    perl automated_mailing.pl inf Brian
    
  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I'd really recommend passing @ARGV as a parameter when calling $functions{$function}->() rather than using it as a global within the subroutine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.