4

What does 1 inside the eval block in perl mean? see the sample code:

eval { 
    print "Ajay";
    1;
} or do { 
    #handle Error Gracefully 
}

Do we tell perl runtime that there was no error that we encountered in the eval block by specifying some positive value at the end of the block?

Or Is it mandatory to specify something at the end?

Ajay Kumar
  • 586
  • 5
  • 21

1 Answers1

3

The two syntactic constructions eval BLOCK and do BLOCK do almost the same thing: both execute their block and return the result of the most recently evaluated expression from that block. The difference is that do might not return at all, whereas eval will always do so.

The reason do might not return is that the code its block is executing might die. That "throws an exception" (not an error, but an exception) that teleports your execution way up the stack to the first dynamically enclosing exception handler.

In contrast, if in the course of executing the eval, the code within it "dies" (read: some exception occurs) rather than itself dying, the eval immediately returns undef and sets the global $@ variable to the exception that made it die.

So that 1; at the end of your eval block guarantees that it returns 1 no matter whether the print statement itself does so. The print operator returns 1 on success and 0 on error, setting the global $! variable to contain the error. It does not die. So if the print failed, then without that 1; the eval itself would appear to have failed if you're only checking it for true or false the way the logical operators like or do.

There is no reason to do this, because print does not throw exceptions.

tchrist
  • 78,834
  • 30
  • 123
  • 180