[Pdx-pm] each within eval

David Wheeler david at kineticode.com
Wed Feb 23 10:24:29 PST 2005


On Feb 23, 2005, at 9:24 AM, Marvin Humphrey wrote:

> while (my ($k, $v) = each %$hashref) {
> 	print "$k => $v\n";
> }
>
> But if I put that same each loop inside $code and eval it, the loop 
> doesn't execute.  each doesn't iterate, and the assignment expression 
> returns 0.  Other code works fine inside the eval, I've got strict and 
> warnings turned on, and I'm checking $@.
>
> This works inside the eval:
>
> foreach my $k (keys %$hashref) {
> 	my $v = $hashref->{$k};
> 	print "$k => $v\n";
> }

That's because %$hashref is unrolled into the string, but each doesn't 
do that (it's an iterator). What you want is a reference to the hash in 
your eval. Use single quotes so that $hashref doesn't evaluate into the 
string, but in the eval. This works for me:

my $hashref = {
     foo => 1,
     bar => 2,
};
my $to_eval = q{
	while (my ($k, $v) = each %$hashref) {
		print "$k => $v\n";
	}

};
eval $to_eval;

Regards,

David



More information about the Pdx-pm-list mailing list