Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Accessing this array ref.

by arnaud99 (Beadle)
on Apr 04, 2013 at 07:37 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-24 23:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found