Jin Kim
Jin Kim

Reputation: 17732

What does the special variable $@ mean in Perl?

I'm trying to understand the following piece of code:

sub foo {
    ...
    if ( $@ ) {
        ...
        die $@;
    }
}

Upvotes: 1

Views: 803

Answers (3)

angel_007
angel_007

Reputation: 103

The if loop should be preceded by eval for it to be able to trap $@.

During an eval(), $@ is always set on failure and cleared on success.

In case whr code inside eval() did not compile, $@ is set to the compilation error.

Upvotes: 0

Nick Lewis
Nick Lewis

Reputation: 4230

$@ is a magic variable containing the error message of the last eval command, if any.

Upvotes: 3

Sinan Ünür
Sinan Ünür

Reputation: 118118

perldoc -f eval:

If there is a syntax error or runtime error, or a "die" statement is executed, an undefined value is returned by "eval", and $@ is set to the error message. If there was no error, $@ is guaranteed to be a null string.

See also perldoc perlvar.

Upvotes: 13

Related Questions