Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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?

like image 323
qntm Avatar asked Jul 16 '15 19:07

qntm


2 Answers

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 = '';
like image 143
LeoNerd Avatar answered Nov 04 '22 19:11

LeoNerd


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.

like image 21
ThisSuitIsBlackNot Avatar answered Nov 04 '22 20:11

ThisSuitIsBlackNot