On Tuesday 08 Dec 2009 11:03:44 Anders Hartman wrote: > Jeff Pang skrev: > > Anders Hartman: > >> 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; > > > > I don't think you want an eval here. > > > > use strict; > > use warnings; > > > > our $abc = "abc\n"; > > > > sub asub { > > print $abc; > > } > > > > asub; > > > > > > Also you may want to know something about Perl's variable scope, see: > > http://perl.plover.com/FAQs/Namespaces.html.en > > Thanks for the link above. > 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 ;-) >
That's because our is a package-scope variable and your previous my is a lexical variable that just happens to live in the global scope. See: http://perl.plover.com/FAQs/Namespaces.html Regarding using string eval "" - you can do the same using UNIVERSAL::can, which would be safer in this case: <<<< __PACKAGE__->can("asub")->(@params); >>>> Perl is a symbolic language. :-) eval "" has some legitimate uses, though, but you should be very cautious with it. Regards, Shlomi Fish -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ My Aphorisms - http://www.shlomifish.org/humour.html Bzr is slower than Subversion in combination with Sourceforge. ( By: http://dazjorz.com/ ) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/