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

Hi Monks,

Greetings.!!!!

I have a small doubt in variable substituation in eval function. Please see the below code and output.

===============

$aa = 4; $bb = 0; eval { $cc = $aa/$bb; }; if ( $@ ) { print "Wrong = Divide by Zero\n"; } else { print "No Exception = Continue your code here\n"; }

OUTPUT:

Wrong = Divide by Zero

===============

But if I use the constant instead of variable, the exception catch is not happening. I am getting the actual run time error.

===============

eval { $cc = 4/0; }; if ( $@ ) { print "Wrong = Divide by Zero\n"; } else { print "No Exception = Continue your code here\n"; }

OUTPUT:

Illegal division by zero at test.pl line 2.

===============

Could anyone let me know the reason for the different output for the same code.

Edited by planetscape - added code tags and rudimentary formatting

( keep:2 edit:28 reap:0 )

Replies are listed 'Best First'.
Re: Variables in eval funcation
by tinita (Parson) on Sep 06, 2006 at 12:41 UTC
    I am getting the actual run time error.
    You are getting a compile time error, that's the difference =)

    perl compiles the code and optimizes 4/0 to its result. if it had been 4/2 then the code would have seen a '2' at runtime.

Re: Variables in eval funcation
by davorg (Chancellor) on Sep 06, 2006 at 12:43 UTC

    As it's a constant expression, Perl tries to evaluate it at compile time and (as you've seen) fails.

    See Sean Burke's article Constants in Perl.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Variables in eval funcation
by imp (Priest) on Sep 06, 2006 at 12:44 UTC
    That error is caught by perl at compile time, as the line in question will never work. Execution is aborted before it starts.
    > perl -MO=Deparse -e 'eval { $cc = 4/0; };' Illegal division by zero at -e line 1.
Re: Variables in eval funcation
by diotalevi (Canon) on Sep 06, 2006 at 13:18 UTC

    The very most recent versions of perl, like 5.9.3+ will do what you hoped for. You'll need to download bleadperl and compile it to try it out.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re: Variables in eval funcation
by NetWallah (Canon) on Sep 06, 2006 at 12:43 UTC
    The constant division is evaluated at "compile-time" - which in the case of perl is "interpretation time", rather than "execution time". What you are seeing is the result of perl complaining about a syntax-type error.

         "For every complex problem, there is a simple answer ... and it is wrong." --H.L. Mencken