PatrickB
PatrickB

Reputation: 256

Why does this return the empty string?

I found a code fragment in production that I didn't really understand. I tried to narrow it down to a simple example:

%hash = {
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry'
};

my $v = "Hello, " . '+' foreach (keys %hash);

print "Value = \"$v\"\n";

When I run this, the value of $v is the empty string, which is surprising. I'm also curious why . '+' foreach( ... ) doesn't cause an error -- I don't even have an operator between '+' and foreach( ... ), how can this possibly not cause a syntax error?

Upvotes: 4

Views: 121

Answers (1)

Quentin
Quentin

Reputation: 943108

You should use warnings;

Reference found where even-sized list expected at test.pl line 3.

You're assigning a single value (a hashref) to %hash instead of a list of key/value pairs.

You should also use strict;.

Use of uninitialized value $v in concatenation (.) or string at test.pl line 12.

You've put my $v inside a for loop, so it is scoped to that loop.

This code is now free of syntax errors:

use strict;
use warnings;

my %hash = (
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry'
);

my $v;

$v = "Hello, " . '+' foreach (keys %hash);

print "Value = \"$v\"\n";

… but you are overwriting $v with the same string ("Hello, " . '+') each time you go around the loop.


how can this possibly not cause a syntax error?

Since you don't have use strict on, lots of horrible things are allowed. It is rarely useful to run without use strict.

I don't even have an operator between '+' and foreach( ... )

Your code is equivalent to:

foreach (keys %hash) {
    my $v = "Hello, " . '+';
}

It wouldn't make sense to put an operator before foreach or after +'.

Upvotes: 8

Related Questions