perl die if a variable is set to undef, correct?

Viewed 365

Many Perl libs returns undef if something internal failed.
For example with DBI :

my $result = $sth->fetchrow_hashref();

To simply stop my program in one line (there's an eval at the top caller), since this unique result is always relevant for me to see if all was ok, and lighter than a try/catch, can I always write:

my $result = $theLibraryCall or die "ERROR ..." 

It also works for value 0.

2 Answers
# Dies if f() returns any false value (incl, but not limited to, undefined)
my $result = f()
   or die ...;

# Dies if f() returns an undefined value
defined( my $result = f() )
   or die ...;

# Dies if f() returns nothing at all
my ($result) = f()
   or die ...;

As you can see, my $result = f() or die ...; will die not just for undefined values, but for all false values.

To only die when an undefined value is returned, use one of the following:

defined( my $result = f() )
   or die ...;
my $result = f()
   // die ...;

Note that these are subtly different. The first performs the assignment before the check, while the other performs the check before the assignment.

Defined-or operator //

Newer version of perl support Defined-or operator - //.

my $result = theLibraryCall() // die "ERROR ...";

In older perl version you may use

defined(  my $result = theLibraryCall() ) || die "ERROR ...";
Related