Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)
# 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...