jkeenan1 has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: eval do {} -- magical variable assignment?
by bart (Canon) on Dec 30, 2006 at 01:12 UTC | |
by jkeenan1 (Deacon) on Dec 30, 2006 at 03:00 UTC | |
|
Re: eval do {} -- magical variable assignment?
by liverpole (Monsignor) on Dec 30, 2006 at 01:08 UTC | |
|
Re: eval do {} -- magical variable assignment?
by shmem (Chancellor) on Dec 30, 2006 at 02:50 UTC | |
by aufflick (Deacon) on Jan 02, 2007 at 07:20 UTC |