Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between return; and return undef; in Perl

Tags:

perl

Is there a difference between a subroutine that does

return; 

and one that does?

return undef; 
like image 813
friedo Avatar asked Aug 08 '10 16:08

friedo


People also ask

What does return do in Perl?

Perl | return() Function return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.

How do I return undef in Perl?

The solution that seems to be obvious to many people, especially who are new to Perl, is to explicitly return undef by writing: return undef;.

How to return value from Perl script?

You can return a value from Perl subroutine as you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.


2 Answers

return; will return an empty list in list context but undef in scalar context. return undef; will always return a single value undef even in list context.

In general, it's usually not a good idea to return undef; from a subroutine normally used in list context:

sub foo { return undef } if ( my @x = foo() ) {     print "oops, we think we got a result"; } 

In general, it's usually not a good idea to return; from a subroutine normally used in scalar context, because it won't behave as the user expects in list context:

sub foo { return } %x = ( 'foo' => foo(), 'bar' => 'baz' ); if ( ! exists $x{'bar'} ) {     print "oops, bar became a value, not a key"; } 

Both of these errors happen quite a bit in practice, the latter more so, perhaps because subs that are expected to return a scalar are more common. And if it's expected to return a scalar, it had better return a scalar.

like image 93
ysth Avatar answered Sep 23 '22 09:09

ysth


Given

sub foo { return; } sub bar { return undef; } 

In scalar context, they behave the same.

my $foo = foo();   # $foo is undef my $bar = bar();   # $bar is undef 

In list context, they behave differently

my @foo = foo();   # @foo is ()  (an empty list) my @bar = bar();   # @bar is ( undef )  (a one-element list) 

Note that a one-element list is a true value in boolean context, even though the only element is undef.

In general, it's usually not a good idea to return undef; from a subroutine, because of how it behaves in context.

like image 26
friedo Avatar answered Sep 24 '22 09:09

friedo