Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Accessing this array ref.

by arnaud99 (Beadle)
on Apr 04, 2013 at 07:37 UTC ( #1026942=note: print w/ replies, xml ) Need Help??


in reply to Accessing this array ref.

Hi

This is a possible other way to come up with the same output.

use Modern::Perl; my $data = [ { 'name' => 'Discount', 'reference' => '100 ', 'type' => 'Paper' }, { 'name' => 'Documents', 'reference' => '100 ', 'type' => 'Paper' }, { 'name' => 'Money', 'reference' => '340 ', 'type' => 'Plastic' }, { 'name' => 'State', 'reference' => '40 ', 'type' => 'Cotton' }, { 'name' => 'Slice', 'reference' => '30 ', 'type' => 'Cotton' }, { 'name' => 'Part', 'reference' => '45 ', 'type' => 'Cotton' }, ]; #recreate a data structure from the existing one, #but this time the main key is the type. my %result; foreach my $elem(@$data) { my $type = $elem->{type}; #create an array ref for that type if (! exists $result{$type} ) { $result{$type} = []; } #store name an reference under that type push @{ $result{$type} }, { name => $elem->{name}, reference => $elem->{reference}, }; } #loop through the new struct, and for each type, #print the list of names and references foreach my $a_type (sort {$a cmp $b} keys %result) { say $a_type; foreach my $a_ref( @{ $result{$a_type} } ) { say "\t", $a_ref->{name}, ': ', $a_ref->{reference}; } }

Output

Cotton State: 40 Slice: 30 Part: 45 Paper Discount: 100 Documents: 100 Plastic Money: 340

Cheers.

Arnaud


Comment on Re: Accessing this array ref.
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1026942]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2014-09-20 23:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (164 votes), past polls