Pankaj Pankaj - 6 months ago 20
Perl Question

duplicate values in hash

Item1 : Box1
Item2 : Box1

Item3 : Box2
Item4 : Box2

I have an output in the form of a hash(listed above)
I want to process it so that output looks like to be

Box1 = {Item1, Item2}
Box2 = {Item3, Item4}

Answer

this is the most I could make based on your requirements:

use strict;
use warnings;

use Data::Dumper;

my %items = (
    Item1 => 'Box1',
    Item2 => 'Box1',

    Item3 => 'Box2',
    Item4 => 'Box2',
);

my %boxes = ();

foreach my $item_name ( keys %items ){
    push @{ $boxes{ $items{$item_name} } }, $item_name;
}

print "Boxes: ".Dumper( \%boxes );

and prints:

Boxes: $VAR1 = {
          'Box1' => [
                      'Item1',
                      'Item2'
                    ],
          'Box2' => [
                      'Item4',
                      'Item3'
                    ]
        };