perl - 在散列键重复中,将值连接到 perl 脚本中的先前键中

标签 perl hash

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

当前输出:

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

预期输出

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

如果键重复,我们如何将这些值与前一个值合并。 如果键与哈希表中存储的最后一个值重复。任何人都可以提供解决方法,我们将不胜感激。

最佳答案

我将使用数组的哈希值,并按照以下方式重写它:

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

关于perl - 在散列键重复中,将值连接到 perl 脚本中的先前键中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38608284/

相关文章:

<STDIN> 上的正则表达式找不到匹配项 - Perl

perl - 是否有将 c99 十六进制浮点符号转换为常规符号的 Perl 模块?

mysql - Perl 中的多行 MySQL

perl - 如何分析这个散列示例的散列?

perl - 我如何检查我是否在 Perl 中下载了整个文件?

javascript - jquery - .hash 在此函数中的意义

objective-c - 在可变 Cocoa 对象上实现 -hash 的技术

ruby 风格 : How to check whether a nested hash element exists

node.js - 如何使用 Passport.js 返回到当前哈希位置?

C++ PBKDF2 问题