Search code examples
perlevalreturn-value

Eval return value


Is it correct code?

my $ttt = eval {
 my @a=(1,2);
 return \@a;
};

print @$ttt[1]. "\n";

I thought that an eval block is evaluated on the fly and does not exist after execution. Are there any minuses in that decision?


Solution

  • The eval block remains part of the code in memory. Is that what you are trying to avoid? If so, this isn't the right way to do it and you should explain more the underlying problem you are trying to solve.

    The code will run, but you are using an array slice in the print where you probably intend to use a simple array dereference:

    print $$ttt[1]. "\n";
    

    You also aren't checking to see if the eval succeeded; the following proceeds to the print and then (if you have warnings enabled) gives a Use of uninitialized value warning:

    my $ttt = eval {
        die "horribly";
        my @a=(1,2);
        return \@a;
    };
    
    print @$ttt[1]. "\n";