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