Calling variable functions in Perl


What I’m trying to say with this title is the following:

# ... lets say we have a value $foo ....
# ... and we want to call method_1 method_2 ... method_N on it
foreach my $method_name (1..N) {
  $method_name = "method_$method_name";
  my $func = *$method_name;
  my $result = &$func($foo);
  # ...
}

The trick is to look up the given name in the symbol table (done by the * operator), and use the obtained pointer to call the function indirectly. This can be used for example in writing test scripts, where you don’t want to copy-paste the same line over and over again.


Leave a Reply

Your email address will not be published. Required fields are marked *