Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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 studying the Monastery: (15)
As of 2015-07-29 16:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (265 votes), past polls