Your problem can be explained by reading the documentation for eval
, as you were using the 2nd form instead of the 1st form:
eval EXPR
eval BLOCK
eval
In the first form, the return value of EXPR
is parsed and executed as if it were a little Perl program. The value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This means, that in particular, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards.
...
In the second form, the code within the BLOCK is parsed only once--at the same time the code surrounding the eval itself was parsed--and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first (see below), while also providing the benefit of checking the code within BLOCK at compile time.
So basically, my @foo = eval { $varname };
is equivalent to my @foo = do { $varname };
except that it does error trapping. Obviously a simple scalar in a void context isn't going to throw any errors, so it's equivalent to my @foo = $varname;
.
If you wanted the other, you have to use my @foo = eval "$varname";
Regardless, you shouldn't be using eval
at all. It's not a tool necessary for beginner programmers, and will only get you in trouble. The only time it's acceptable for a beginner to eval
is in the RHS of a regular expression, s{search}{ BLOCK }e;
Therefore follow tobyink's advice and use references.