Here is a Perl program:
use strict;
use warnings;
use Data::Dumper;
sub f {
foreach (()) { }
}
print Dumper(f());
This outputs:
$VAR1 = '';
Since no value is explicitly returned from f
, and no expressions are evaluated inside it, shouldn't the result be undef
? Where did the empty string come from?
It hasn't quite returned the empty string; it has returned "false", an internal Perl value (called PL_no
). This false value is numerically zero but stringily empty. Data::Dumper
can't represent it directly as PL_no
and so chooses a representation which will work.
Other ways you can generate it:
$ perl -MData::Dumper -E 'say Dumper(1 eq 2)'
$VAR1 = '';
Since no value is explicitly returned from
f
, and no expressions are evaluated inside it, shouldn't the result beundef
?
Nope. perldoc perlsub
says the return value is unspecified:
If no
return
is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like aforeach
or awhile
, the returned value is unspecified.
"Unspecified" is short for "we're not going to document the exact behavior because we could change it at any time and you shouldn't rely on it." Right now, it returns PL_no
as LeoNerd explained; in a future Perl version, it could return undef
, or something else altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With