vmraj has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I need to invoke the method based on the user input. I have the following script and it works.

Can you please explain how does this line work? $func->(%opts);

This line $func->(%opts) do not have any return statement; But it returns the value properly

Thanks
Code: #!/usr/local/bin/perl use strict; use Getopt::Long qw(:config gnu_getopt); ########################################### # Parses the commad line arguments # Example: callfunction.pl -action getInfo ########################################### sub parse_args { my %opts; GetOptions(\%opts, "action=s", ); return %opts; } my %opts = parse_args(); my $action = $opts{action}; my $output = call_function($action, %opts); =head call_function ($function_name, %params) This method invokes the appropriate subroutine based on the funcname p +assed =cut sub call_function { my $funcname = shift; my %opts = @_; my $package = 'main'; if ( my $func = UNIVERSAL::can($package, $funcname) ) { $func->(%opts); } else { die "no such function $package\::$funcname\n"; } } sub getInfo { my $msg = shift; return $msg; }

Replies are listed 'Best First'.
Re: How to invoke the method dynamically using universal::can
by ikegami (Patriarch) on Sep 23, 2010 at 15:39 UTC

    Note that can makes no sense for function calls. It checks inheritance. For functions, you should use something like the following:

    sub call_function { my $funcname = shift; my $package = caller(); my $qfuncname = "${package}::$funcname"; no strict 'refs'; exists(&$qfuncname) or die("no such function $qfuncname\n"); return &{$qfuncname}(@_); } sub f { print "f\n"; } call_function('f'); call_function('g');
    f no such function main::g
Re: How to invoke the method dynamically using universal::can
by Corion (Patriarch) on Sep 23, 2010 at 15:18 UTC

    See return:

    (In the absence of an explicit return, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.)