开发者

Filling hash of multi-dimensional arrays in perl

开发者 https://www.devze.com 2023-01-24 01:56 出处:网络
Given three scalars, what is the perl syntax to fill a hash in which one of the scalars is the key, another determines which of two arrays is filled, and the third is appended to one of the arrays? Fo

Given three scalars, what is the perl syntax to fill a hash in which one of the scalars is the key, another determines which of two arrays is filled, and the third is appended to one of the arrays? For example:

my $weekday = "Monday";
my $kind    = "Good";
my $event   = "Birthday";

and given only the scalars and not their particular values, obtained inside a loop, I want a hash like:

my %Weekdays = {
      'Monday' => [
                    ["Birthday", "Holiday"],     # The Good array
                    ["Exam", "Workday"]          # The Bad array
                  ]
      'Saturday' => [
                    ["RoadTrip", "Concert", "Movie"],
                    ["Yardwork", "VisitMIL"]
                  ]
}

I know how to append a value to an array in a hash, such as if the key is a single array:

push( @{ $Weekdays{$weekday} }, $event);

Used in a loop, that could give me:

%Weekdays = {
        'Monday' => [
                    'Birthday',
                    'Holiday',
                    'Exam',
                    'Workday'
                    ]
}

I suppose the hash key is the particular weekday, and the value should be a two dimensional array. I don't know the perl syntax to, say, push Birthday 开发者_C百科into the hash as element [0][0] of the weekday array, and the next time through the loop, push another event in as [0][1] or [1][0]. Similarly, I don't know the syntax to access same.


Using your variables, I'd write it like this:

push @{ $Weekdays{ $weekday }[ $kind eq 'Good' ? 0 : 1 ] }, $event;

However, I'd probably just make the Good/Bad specifiers keys as well. And given my druthers:

use autobox::Core; 
( $Weekdays{ $weekday }{ $kind } ||= [] )->push( $event );

Note that the way I've written it here, neither expression cares whether or not an array exists before we start.


Is there some reason that

 push @{ $Weekdays{Monday}[0] }, "whatever";

isn’t working for you?

0

精彩评论

暂无评论...
验证码 换一张
取 消