4

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?

1
  • foreach is also statement modifier (similar to more common if modifier, e.g. $y = $z if defined $z;). Commented Apr 15, 2014 at 20:24

1 Answer 1

8

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 +'.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh Perl, you sneaky thing, you. Thanks for the explanation.

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.