Back to Top

Tuesday, September 30, 2008

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.


Post a Comment

You can use some HTML tags, such as <b>, <i>, <a>. Comments are moderated, so there will be a delay until the comment appears. However if you comment, I follow.