ssr1012 ssr1012 - 4 months ago 7
Perl Question

In hashes key duplicated join the Value into the previous keys in perl script

my %colorfigshash = ();
my $tempcnt = <DATA>;
while($tempcnt=~m/Placement of Figure (?:[^\{]*)\{([^\{\}]*)\} Page ([^\n]*)\n/sg)
{
$colorfigshash{$1} = $2;
}

use Data::Dumper;
print Dumper \%colorfigshash;

__DATA__
Placement of Figure \hbox {10.7} Page 216
Pages in Color: 216
Placement of Figure \hbox {10.7} Page 217
Pages in Color: 217


Current Output:

$VAR1 = {
'10.7' => '216'
};


Expected Output

$VAR1 = {
'10.7' => '216-217'
};


How could we merge the values with previous one if the keys are duplicated.
If the Keys duplicated the last Value stored in the hashes table. Anyone could give a path to solve also it would be appreciated.

Answer

I would use a hash of arrays, and re-write it something like this:

my %colorfigshash;

while(<DATA>) { 
    chomp; 
    next unless /^Placement/;
    my ($placement) = /\{(\d+\.\d+)\}/;
    my ($page) = /Page (\d+)/;
    push @{$colorfigshash{$placement}}, $page;
}

for (keys %colorfigshash){
    print "$_ ";
    print join ('-', @{$colorfigshash{$_}}), "\n";
}

10.7 216-217
Comments