shane1717
shane1717

Reputation: 97

push values of multidimensional array to an array in perl

I have this multidimensional hash %HASH:

 'BBBL' => {
',                   'VALUE' => 'CASH
                     'DATES' => '20163112'
                      },
  'AAA' => {
',                   'VALUE' => '70
                     'DATES' => '20170602'
  'CCC' => {
',                   'VALUE' => '70
                     'DATES' => '20170602'

and for each of AAA BBB and CCC i want to push the DATES into an array.

foreach my $symbol (keys %HASH){
     my @dates = values %HASH;
    }

but that gives me:

            'VALUE' => 'CASH
            'DATES' => '20163112'
          },
          {
',          'VALUE' => '90
            'DATES' => '20170802'
          },
          {
',          'VALUE' => '90
            'DATES' => '20171702'
          }
        ];

and I have no idea how to get just the dates.

Upvotes: 1

Views: 287

Answers (1)

melpomene
melpomene

Reputation: 85767

You could do it like this:

my @dates;
for my $symbol (keys %HASH){
    push @dates, $HASH{$symbol}{DATES};
}

This could be simplified to:

my @dates;
for my $subhash (values %HASH){
    push @dates, $subhash->{DATES};
}

Which in turn could be rewritten as:

my @dates = map $_->{DATES}, values %HASH;

Side note: It seems like your VALUE fields contain a carriage return (CR, \r) at the end. If you used Data::Dumper to produce your output, you might want to set $Data::Dumper::Useqq = 1; to make the dump more readable.

Upvotes: 4

Related Questions