2016-07-27 45 views
2
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 

電流輸出:在哈希鍵複製加盟值到以前的密鑰在perl腳本

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

期望輸出

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

我們怎麼能合併與以前的一個,如果該值密鑰是重複的。 如果Keys複製存儲在散列表中的最後一個值。任何人都可以提供解決方案,也將不勝感激。

+0

是不是你的電流輸出'10.7' =>「217'? – xxfelixxx

+0

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

+1

策略是將值推送到由'$ 1'索引的數組。然後,您可以處理數組中的值以生成更友好的字符串。您可以推送@ {$ colorfigshash {$ 1}},$ 2;' – xxfelixxx

回答

3

我會用數組的哈希,並沿着這些線路重新寫:

use strict; 
use warnings; 

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"; 
} 

__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 

10.7 216-217