Alex Rivera | Logout

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

Asked 2010-08-08T16:36:25.320
29

Is there a difference between a subroutine that does

return;

and one that does?

return undef;
Edit
Report

1 Answer

23

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.

answered 2010-08-08T16:38:05.360

Your Answer