Why does Perl treat a hash element as a list context when declaring?

Given this code:

#!/usr/bin/perl -w

use strict;
use warnings;

sub foo {
    return wantarray ? () : "value1";
}

my $hash = {
    key1 => foo(),
    key2 => 'value2'
};

use Data::Dumper;
print Dumper($hash);

I get the following output:

$VAR1 = {
  'key1' => 'key2',
  'value2' => undef
};

When I expect:

$VAR1 = {
  'key1' => 'value1',
  'key2' => 'value2'
};

I understand that a hash is a kind of an even-sized array (as evidenced by the warning “An odd number of elements in a hash assignment” that I get), but a hash element can only be a scalar, why should the compiler provide an array context?

I found this using the param function of the CGI module when assigning the hash directly. The foo () function above was a call to CGI :: param ('mistyped_url_param'), which returned an empty array, destroying (rotating?) The hash structure.

+3
source share
2 answers

. , " "

:

my $hash = {
    key1 => foo(),
    key2 => 'value2'
};

:

my $hash = {
    'key1', foo(), 'key2', 'value2'
};

... , :

. , scalar foo()

+7

- , . , . Perl , , . => , , Perl - .

.., .

:

 my $hash = { 
      a => 'A',  
      map( uc, 'd' .. 'f' ),
      return_list( @args ), 
      z => 'Z' 
      };

- , , scalar:

 my $hash = { 
      a => 'A',  
      map( uc, 'd' .. 'f' ),
      'g' => scalar return_item( @args ), 
      z => 'Z' 
      };
+3

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


All Articles