I just noticed that return in an eval { ... } block will return from the block, not from the function containing it.

That's different from any other kind of control block, and thus surprising.

Furthermore, there's no way to return a value out of an arbitrary block (say, a do {...} block) other than the result of the last evaluated statement within it. That means there is no explicit "this is my value!" marker, and to stop early you have to put the rest of it around an if statement, or use a temporary variable, or somesuch.

With the block form of eval being used mainly as a "try" construct, rather than "define an anonomous sub and call it immediatly with no arguments", this doesn't really fit anymore.

—John

Replies are listed 'Best First'.
Re: return from eval
by MarkM (Curate) on Jan 22, 2003 at 22:42 UTC

    If you are using eval{} as a try, it is not a long stretch to consider using "if ($@ =~ /^RETURN/) {" as a catch, and return from there.

    Use of eval{} as 'try' is more of a convenience than a specifically designed language construct. Perl never claimed to support 'try' in Perl 5.x.

Re: return from eval
by demerphq (Chancellor) on Jan 24, 2003 at 18:34 UTC
    With regard to the do{} you can emulate the behaviour you want fairily easily.
    my $foo=do{ my $return; { unless ($bar) { $return=$baz; last; } elsif ($bar==1) { $return=$bob; last; } $return=fnaggle(fubar(foo(bar($bar)))); } $return; };
    As for the eval, MarkM suggested a work around.

    With the block form of eval being used mainly as a "try" construct, rather than "define an anonomous sub and call it immediatly with no arguments", this doesn't really fit anymore.

    Interesting thought, and I think you have a point there. Unfortunately as we all know theres nothing that can be done about it.

    --- demerphq
    my friends call me, usually because I'm late....