What does "!$@" mean in Perl?

Viewed 133

I don't know Perl. I'm trying to read some Perl code that I didn't write, and I've been stuck for a day or two on this line:

use constant RUNTIME => eval "use Time::SoFar qw( runinterval )" || !$@;

I've managed to piece together most of it, but I can't figure out the last bit, !$@.

This isn't contained in any of the tutorials I've read, and it isn't clear what page of documentation I should look for, since I don't know any keywords related to whatever this is.

Web searching for random symbols gives no results, since most search engines ignore them (including Stack Overflow's, evidently).

I can't break this down into simpler components, either. I recognize $ and @ as sigils for scalar and array variables, but that's clearly not how they're being used here. Searching for them individually only gives results for these variable sigils.

I need an expert, then. What does !$@ mean in this context?

4 Answers

Although it looks rather like a censored swear word, it actually breaks down into ! and $@.

Perl has a number of "special variables" which have single-character names; they also have longer names enabled with the directive use English;

You can find a list on the perlvar page of the perl manual (should also be available by running perldoc perlvar), which specifies $@, English name $EVAL_ERROR, as:

The Perl error from the last eval operator, i.e. the last exception that was caught. For eval BLOCK, this is either a runtime error message or the string or reference die was called with. The eval STRING form also catches syntax errors and other compile time exceptions.

If no error occurs, eval sets $@ to the empty string.

This is then passed to !, which is the "not" operator, which is going to treat the string in $@ as a boolean.

  • If the error string is empty, it will be false, "not false" is true, which will become "1"
  • If the error string is not empty, it will be true, "not true" is false, which will become ""

! is the negation operator (perlop), $@ is the special variable that holds the last exception thrown (perlvar#$@).

The constant RUNTIME will be set to 1 if the use clause was executed successfully. Otherwise, it will be set to the empty string.

$@ is a variable. It's documented in perlvar. It contains the exception that was thrown by the most recent eval, or undef if there was none. ! is just the not operator.

It sort of looks like a cartoon dialogue curse word doesn't it?

Take it one symbol at a time. The ! is boolean NOT, so if the following value is True it will become False, and vice versa.

The $ starts a scalar value. $@ is found in man perlvar and it is the error value output from the last eval call.

Related