Håkon Hægland
Håkon Hægland

Reputation: 40778

Initialize a set of hash keys using slicing in Perl

I am trying to initialize a hash using slicing:

use warnings;
use strict;
use Data::Dump qw(dump);

my %h;
my $a=['a','b'];

@h{@$a}=(1)x@$a;
dump(%h);

This works fine, but if I try to do a sub hash, for example %h{test}

@h{test}{@$a}=(1)x@$a;

I get error:

Scalar value @h{test} better written as $h{test} at ./p.pl line 14.
syntax error at ./p.pl line 14, near "}{"
Execution of ./p.pl aborted due to compilation errors.

Upvotes: 2

Views: 197

Answers (2)

Len Jaffe
Len Jaffe

Reputation: 3484

The compiler sees the '@' and thinks to itself 'array', then sees the '{' and says 'wait, what? that's a hash index indicator. Game over man.' So turn the @ into a $.

Upvotes: -1

Vadim Pushtaev
Vadim Pushtaev

Reputation: 2353

You should use @{ $h{test} }{ @$a }=(1)x@$a; since hash contains hash reference, not hash.

use warnings;
use strict;
use Data::Dumper;

my %h;
my $a=['a','b'];

@{ $h{test} }{ @$a }=(1)x@$a;
print Dumper(\%h);

Output is:

$VAR1 = {
          'test' => {
                      'a' => 1,
                      'b' => 1
                    }
        };

See also: Perl: Hash ref accessing array of keys

Upvotes: 8

Related Questions