AidanLee has asked for the wisdom of the Perl Monks concerning the following question:

hi all,

I've got a subroutine that uses a couple of eval's to determine where to store a certain piece of information. I've got a hash, $tmp_record and use a join to determine where in the bowels of that hash the value is stored. The variable storing the array for the path is complex, but here is the gist of it:

my $code_to_eval = ( defined $self->{$key}{path} ) ? '$tmp_record{' . join( '}{', (@{$self->{$key}{path} +},$key) ) . '} = $value' : '$tmp_record{'.$key.'} = $value'; #and then I run: eval $code_to_eval or warn @_;

If people are familiar with my ongoing postings, this relates to the ideas at the bottom of Re: Building and returning structured records from a query.

This works great and does exactly what i want to. This is why I was quite suprised when i found an error in my warning logs:

csResource::Registry=HASH(0x1a6f03c)

I'm running under strict and diagnostics. Any ideas what might be causing this? Thanks much.

Replies are listed 'Best First'.
Re: Eval errors though code is successful
by tadman (Prior) on Jul 09, 2001 at 07:46 UTC
    Using eval for this kind of thing might be a little over the top. It works, yes, but being a dynamically compiled thing can cause problems. Personally, I would have implemented it without the eval. The code below is a little more "verbose", but most of it is standard issue variable declarations:
    sub FindRecord { my ($self) = shift; my ($key) = @_; my $ref = \{$self->{$key}}; if (defined $ref->{path}) { my $path = $ref->{path}; foreach my $bit (@$path) { $ref = $ref->{$bit}; } } return $ref; } # ... sub SomeFunc { my ($self) = shift; # ... ${$self->FindRecord($key)} = $value; }
    This, of course, could also be declared as an 'lvalue' function which would eliminate the ${} prefix. lvalue functions are fun, and I hope that they don't take them away any time soon.

    NB: Code untested, used for demonstration purposes.
      Nice approach. I was looking for something similar to this a while back when I first concocted the eval solution. Your particular example doesn't quite do what I need, but I can see how to get there from here. Thanks for the suggestions.
Re: Eval errors though code is successful
by bikeNomad (Priest) on Jul 09, 2001 at 07:45 UTC
    eval returns the value of what you evaluated. In this case, it returned something that was false. This does not mean that it failed. And return @_ is not appropriate.

    Instead, you want to test $@, which is set if and only if there is an error:

    eval $code_to_eval; warn $@ if $@;
      /me feels like slapping my forehead. thanks, bikeNomad. too much coding.... :)