1

I have a hash that holds for each record an anonymous hash with 2 elements: an array and a hash. I want to initialize this subsidiary hash with a list of keys.

I know hash slices can be used when you use a normal hash (not a ref) and use both a key list and values list.

My code is like this

my %records;
my $key = "key1";
my @states = ( "state1", "state2", "state3" );

$records{$key} = {
    numbers => [],
    states  => %{@states} #This is wrong !
};

EDIT (marked as duplicate): This question asks how to add multiple keys to an anonymous hash.

10
  • Slices are cool, but you don't have to use them everywhere. Just do my $states = { ... }; $records{$key} = { states => $states }; Commented Aug 28, 2015 at 20:49
  • 1
    or states => { map { $_ => undef } @states }. Commented Aug 28, 2015 at 21:09
  • 1
    I could have sworn somebody asked this before, but the closest I could find was Anonymous Hash Slices - syntax? Commented Aug 28, 2015 at 21:14
  • 1
    Shorter is not always better. Generally you should shoot for readability rather than brevity. Commented Aug 28, 2015 at 21:16
  • 1
    You should show what you want %records to look like. It's puzzling that you have only keys for your hash and no values Commented Aug 28, 2015 at 21:45

1 Answer 1

3

It's puzzling that you have only keys for your hash and no values. This code will set the value of each element of $records{$key}{states} to undef

my %records;
my $key = "key1";
my @states = ( "state1", "state2", "state3" );

$records{$key} = {
    numbers => [],
    states  => { map { ( $_ => undef ) } @states },
};

But it would be clearer to build a proper hash temporarily and assign a reference to it to the data structure. I've enclosed the entire assignment process in its own block so that I can declare a temporary lexical hash %states

{
    my %states;
    @states{@states} = ();

    $records{$key} = {
        numbers => [],
        states  => \%states,
    };
}

But note that it's generally better if hash elements don't exist at all rather than create them with undefined values. There is no need to preallocate the elements of a hash like this, just leave it empty like you did with the array

$records{$key} = {
    numbers => [],
    states  => {},
}
Sign up to request clarification or add additional context in comments.

Comments

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.