qntm
qntm

Reputation: 4407

Why does this (mostly) empty Perl subroutine return an empty string?

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?

Upvotes: 9

Views: 535

Answers (2)

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

Since no value is explicitly returned from f, and no expressions are evaluated inside it, shouldn't the result be undef?

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 a foreach or a while, 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.

Upvotes: 6

LeoNerd
LeoNerd

Reputation: 8532

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 = '';

Upvotes: 13

Related Questions