|
|
On Dec 8, 12:08 am, an...@xxxxxxxxxx (Anders Hartman) wrote:
> 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;
>
> with the error:
>
> Use of uninitialized value in print at ...
>
> asub should see the $abc variable in the main program, but doesn't.
> How do I make asub reference variables in the main program?
>
$abc is a lexical variable with file scope and, since the sub's
definition
occurs before $abc is defined, won't be visible. However, $abc would
have printed with the following earlier placement:
my $abc = ...;
...
sub {print $abc; ... }
Since, however, you declared 'our $abc' inside the sub, any lexically
declared $abc won't be seen.
With the 'our $abc', you'd need a global $abc. Either:
eval ...
$::abc = "abc\n"; # or just: $abc = "abc\n" with: use vars
'$abc'
or just:
eval ...
our $abc = "abc\n";
Also, in this case, I'd write the eval for compile-time and check
for errors:
eval { asub() };
die $@ if $@;
--
Charles DeRykus
|
|