从字符串构建哈希
我在 perl 上有以下字符串:
my $string = xyz;1;xyz;2;a;2;b;2
我想在该字符串之后构建一个散列,如下所示:
my @array =split /;/,$string;
$hash{xyz} =(1,2);
$hash{b}=(2);
$hahs{a}=(2);
perl 的方法是什么?
I have the below string on perl :
my $string = xyz;1;xyz;2;a;2;b;2
i want to build a hash after for this string like below :
my @array =split /;/,$string;
$hash{xyz} =(1,2);
$hash{b}=(2);
$hahs{a}=(2);
what is the perl way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能最简单(标准)的方法是
List::MoreUtils: :natatime
然而,抽象出我可能想再次做的部分......
Probably the easiest (standard) way to do this is
List::MoreUtils::natatime
However abstracting out the parts that I would probably want to do again...
实际上
会更好,因为这不会吃掉你原来的字符串。
Actually
would be better, since that doesn't eat up your original string.
假设您希望同一键的多个值成为数组引用,那么一种方法是这样的:
使用您的数据,这将产生如下结构
Assuming you want the multiple values for the same key to be an array reference, then one way to do it is like this:
With your data, this will result in a structure like
Drats:你有重复的键...我想用
map
或grep
做一些事情。这很容易理解:
即使密钥不在字符串中,该程序也会工作。例如,即使
xyz
被其他值对分隔,以下内容也将起作用:我假设
$hash{b}=(2);
意味着您想要$hash{b}
的值是对单个成员数组的引用。这是正确的吗?Drats: You have repeating keys... I wanted to do something with
map
orgrep
.This is fairly simple to understand:
This program will work even if the key is not together in your string. For example, the following will work even though
xyz
is separated by the other value pairs:I am assuming that
$hash{b}=(2);
means you want the value of$hash{b}
to be a reference to a single member array. Is that correct?