9

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?

0

2 Answers 2

13

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 = '';
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know why "false" is returned rather than any other value?
In list context the returned value is the (truthy) single-element list (PL_no), how is that the right thing? The logical value to return would be undef.
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.