Why does this return an empty string?

I found a piece of code in production that I really didn't understand. I tried narrowing 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 value, the value of $ v is an empty string, which is surprising. I am also curious why. '+' foreach (...) does not cause an error - I don’t even have an operator between '+' and foreach (...), how can this not cause a syntax error?

+4
source share
1 answer

You should use warnings;

The link is found where the expected list of dimensional dimensions is expected in the line test.pl 3.

You assign a single value (hashref) to %hasha list of key / value pairs instead.

You must also use strict;.

$v (.) test.pl 12.

my $v for, .

:

use strict;
use warnings;

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

my $v;

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

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

... $v ("Hello, " . '+') , .


?

use strict on, . use strict.

'+' foreach( ... )

:

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

foreach +'.

+8

Source: https://habr.com/ru/post/1535626/


All Articles