简体   繁体   中英

Perl flattening arrays from hash results in ARRAY

I'm trying to flatten an array contained in a hash with the following:

foreach my $key (keys %months) {
    foreach (%months->{$key}) {
       %months->{$key} = $key . ' ' . join(',', %months->{$key});
    }
}

I'm trying to generate a string of days like like:

"2, 11, 15, 18, 25"

But I get:

ARRAY(0x5a2e7b0)

Structure of %months is:

months {
    Jan: [1,5,30],
    Feb: [2,6]
}

An " array contained in a hash " must be an array reference , a scalar (what a hash value must be).

Thus when you retrieve it you need to dereference it

my @ary = @{ $months->{$key} };

and you can generate the desired string out of it

my $date_list = join ', ', @{ $months->{$key} };

This assumes that $months is a hashref , judged by the arrow-dereferencing from the question.Then % in front of months is wrong. There is also an extra loop. For the shown data

foreach my $key (keys %$months) {
    say join ', ', $key, @{$months->$key}};
}

or

say join ', ', $_, @{$months->$_}}  for keys %$months;

The code in the question applies to data with yet another level of nesting

foreach my $key (keys %$months) {
    foreach ($months->{$key}) {
       say join ', ', @{$months->{$key}->{$_}};
    }
}

to join only the last-level arrayref data, or

   say join ', ', $key, $_, @{$months->{$key}->{$_}};

to join both keys and the arrayref data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM