my $fh = open_file("<", $file, $verbose); my $class; eval do { local $/; <$fh> }; die $@ if $@; close $fh; return $class;
$file, when opened (I suspect) looks like this:
$class = { big => "hashref" };
When I surround this code with print statements for debugging, I find that $class is undefined when first declared but fully populated at the point where it is to be returned -- even though there is no explicit assignment to $class in this program.
Let me illustrate. Suppose that I have a file called alpha.txt that reads like this:
$class = { alpha => 'beta', gamma => 'delta', epsilon => 'zeta', };
In my main program, I then call:
use strict; use Data::Dumper; my $file = q{alpha.txt}; my $class; open my $fh, "<", $file or die "Unable to open: $!"; eval do { local $/; <$fh> }; die $@ if $@; close $fh or die "Unable to close: $!"; print Dumper $class;
I get this output:
$VAR1 = { 'gamma' => 'delta', 'epsilon' => 'zeta', 'alpha' => 'beta' };
Now, I would not have been surprised to get this result if my code had read:
use strict; use Data::Dumper; our $class; my $file = q{alpha.txt}; require $file; print Dumper $class;
... which produces exactly the same output. But in this case I know I have to use an our variable; a my variable will not suffice. So how come eval do {} enables me to get away with a my variable in the former case?
Thank you very much.
In reply to eval do {} -- magical variable assignment? by jkeenan1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |