3

Can I call a subroutine by taking its name dynamically as below?

printf "Enter subroutine name: ";
$var1 = <STDIN>;      # Input is E111;
$var1();

Function E111:

sub E111(){
    printf "Hi, this is E111 & Bye \n";
}

Is there a possibility to do it like this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sriram P
  • 179
  • 1
  • 13
  • Follow the good advice of @zdim and use a dispatch table, but of course dynamic function calls are possible in perl: https://perldoc.perl.org/functions/eval.html – xxfelixxx Apr 05 '17 at 01:57
  • Possible duplicate of [Calling perl subroutines from the command line](http://stackoverflow.com/questions/23039028/calling-perl-subroutines-from-the-command-line) – Chankey Pathak Apr 28 '17 at 08:09

2 Answers2

7

There are very few hard limits on what you can do in Perl, but this is one of those places that you don't want to go to. One normal way about it is to use a dispatch table

my %call = (
    'name_1' => sub { function body },   # inline, anonymous subroutine
    'name_2' => \&func,                  # or take a reference to a sub
    ...
);

where sub {} is an anonymous subroutine, so the value for name_1 is a code reference.

Then you use it as

my $name = <STDIN>;
chomp $name;

$call{$name}->(@arguments);  # runs the code associated with $name

This finds the key $name in the hash and dereferences its value, the coderef; so it runs that code.

Documentation: overview perlintro, tutorial perlreftut, and references perlref and perlsub.

zdim
  • 64,580
  • 5
  • 52
  • 81
0

A solution:

print "Enter subroutine name:";

$var1 = <STDIN>;
chomp($var1);

eval "$var1()";

sub E111 {
    print "Hi this is E111 & Bye \n";
}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Sachin Dangol
  • 504
  • 5
  • 13