我在 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 的方法是什么?
我在 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 的方法是什么?
my $string = "xyz;1;xyz;2;a;2;b;2";
my %hash;
push @{$hash{$1}}, $2 while $string =~ s/^(\w+);(\d+);?//g;
实际上
push @{$hash{$1}}, $2 while $string =~ m/(\w+);(\d+);?/g;
会更好,因为这不会占用您的原始字符串。
假设您希望同一键的多个值作为数组引用,那么一种方法是这样的:
my @values = split /;/, $string;
my %hash;
while( @values ) {
my $key = shift @values;
my $val = shift @values;
if ( exists $hash{$key} && !ref $hash{$key} ) {
# upgrade to arrayref
$hash{$key} = [ $hash{$key}, $val ];
} elsif ( ref $hash{$key} ) {
push @{ $hash{$key} }, $val;
} else {
$hash{$key} = $val;
}
}
使用您的数据,这将产生类似的结构
{
'a' => '2',
'b' => '2',
'xyz' => [
'1',
'2'
]
};
map
Drats:你有重复键……我想用or做点什么grep
。
这很容易理解:
my $string = "xyz;1;xyz;2;a;2;b;2";
my @array = split /;/ => $string;
my %hash;
while (@array) {
my ($key, $value) = splice @array, 0, 2;
$hash{$key} = [] if not exists $hash{$key};
push @{$hash{$key}}, $value;
}
即使密钥不在您的字符串中,该程序也将起作用。例如,即使xyz
由其他值对分隔,以下内容也将起作用:
my $string = "xyz;1;a;2;b;2;xyz;2";
我假设这$hash{b}=(2);
意味着您希望 的值是$hash{b}
对单个成员数组的引用。那是对的吗?
可能最简单(标准)的方法是List::MoreUtils::natatime
use List::MoreUtils qw<natatime>;
my $iter = natatime 2 => split /;/, 'xyz;1;xyz;2;a;2;b;2';
my %hash;
while ( my ( $k, $v ) = $iter->()) {
push @{ $hash{ $k } }, $v;
}
然而,抽象出我可能想再次做的部分......
use List::MoreUtils qw<natatime>;
sub pairs {
my $iter = natatime 2 => @_;
my @pairs;
while ( my ( $k, $v ) = $iter->()) {
push @pairs, [ $k, $v ];
}
return @pairs;
}
sub multi_hash {
my %h;
push @{ $h{ $_->[0] } }, $_->[1] foreach &pairs;
return wantarray ? %h : \%h;
}
my %hash = multi_hash( split /;/, 'xyz;1;xyz;2;a;2;b;2' );