Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this return the empty string?

Tags:

perl

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?

like image 992
PatrickB Avatar asked Feb 14 '23 06:02

PatrickB


1 Answers

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

like image 58
Quentin Avatar answered Feb 28 '23 01:02

Quentin