当密钥在perl中相同时,连接散列值 [英] concatenate hash values when key is same in perl

查看:102
本文介绍了当密钥在perl中相同时,连接散列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  abc => 1 
hello => 32
abc => 4
hello => 23
hello => 12
xyz => 18

我们如何连接键值相同的值。
所以输出将是:

$ b $ pre $ code abc =>1,4
hello =>23,12,32
xyz =>18。

我试着通过键排序哈希,然后检查每个键,如果它们是相同的,然后连接值,但我没有得到如何比较两个键在同一个循环。


在此先感谢。

解决方案

确切的工作方式取决于数据的真实来源,但是这个程序展示了一种从 DATA 文件句柄读取信息的方法来构建和转储一个散列。

散列的值是匿名数组,包含所有对应于同一个键的值。

  use strict; 
使用警告;

my%data; (< DATA>){
my($ k,$ v)= / \ w + / g;

;
push @ {$ data {$ k}},$ v;


for $ k(sort key%data){
printf%s =>%s\\\
,$ k,join',' @ {$ data {$ k}};
}

__DATA__
abc => 1
hello => 32
abc => 4
hello => 23
hello => 12
xyz => 18

输出 $ b

  abc => 1,4 
hello => 32,23,12
xyz => 18


I have a hash something like :

abc=>1
hello=>32
abc=>4
hello=>23
hello=>12
xyz=>18

how can we concatenate the values, whose keys are same. So the output will be:

abc=>"1,4"
hello=>"23,12,32"
xyz=>"18".

I tried by sorting the hash by keys then checking for each key, if they are same then concatenate the value, but i am not getting that how to compare two keys in same loop.

Thanks in advance.

解决方案

The exact way this works depends on the real source of your data, but this program shows a way to read the information from the DATA filehandle to build and dump a hash.

The values of the hash are anonymous arrays that contain all the values corresponding to the same key.

use strict;
use warnings;

my %data;

while (<DATA>) {
  my ($k, $v) = /\w+/g;
  push @{ $data{$k} }, $v;
}

for my $k (sort keys %data) {
  printf "%s => %s\n", $k, join ',', @{ $data{$k} };
}

__DATA__
abc=>1
hello=>32
abc=>4
hello=>23
hello=>12
xyz=>18

output

abc => 1,4
hello => 32,23,12
xyz => 18

这篇关于当密钥在perl中相同时,连接散列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆