2009/12/8 Anders Hartman <an...@melerit.se>:
>>> Hello,
>>> I which to use eval to execute subroutines dynamically.
>>> The following code snippet fails:
>>>
>>> #!/usr/bin/perl
>>>
>>> use strict;
>>> use warnings;
>>>
>>> sub asub {
>>>  our $abc;
>>>  print $abc;
>>> }
>>>
>>> my $abc = "abc\n";
>>> eval "asub";
>>> exit 0;

> However, I DO need to use eval because the names of the functions to call
> are determined dynamically at runtime.
> A solution has been found: If I change the line
> my $abc = "abc\n";
> in the main program to
> our $abc = "abc\n";
> everything works. I don't quite see why though ;-)


What happened is that you couldn't insert the round peg through the
square hole, so you brought a bigger hammer and banged on it until it
did go through, but broke half of the box in the process.

What the second 'our' did was basically nothing, since it refers to
the first 'our' which is declared in the function:

sub asub {
 our $abc = 'blue';
 print $abc;
}

my $abc = "abc\n";
eval "asub";
exit 0

this will return 'blue', not "abc\n".

What I suggest you actually do, is use a dispatch table:

my %function_calls= (
  "asub" => \&asub,
  "another_sub" => \&another_sub,);

and so on.

-- 
Erez

"The government forgets that George Orwell's 1984 was a warning, and
not a blueprint"
http://www.nonviolent-conflict.org/ -- http://www.whyweprotest.org/

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to