Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/65919825/perl-die-if-a-variable-is-set-to-undef-correct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
863 views
Welcome To Ask or Share your Answers For Others

1 Answer

# 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...