将哈希的哈希值重写为并行数组

时间:2017-04-27 20:18:03

标签: perl

我需要将哈希散列中的值重写为并行数组。

具体来说,我想转型

my %cars;
$cars{123} = { owner => "Mark",   color => "black", maxspeed  = "260" };
$cars{124} = { owner => "Jason",  color => "red",   maxspeed => "230" };
$cars{125} = { owner => "Sumaya", color => "pink",  maxspeed => "200" };

my @owners    = ( "Mark",  "Jason", "Sumaya" );
my @colors    = ( "black", "red",   "pink"   );
my @maxspeeds = ( "260",   "230",   "200"    );

1 个答案:

答案 0 :(得分:3)

这可以使用

来实现
my @ids       = keys(%cars);
my @owners    = map { $_->{ owner    } } @cars{@ids};
my @colors    = map { $_->{ color    } } @cars{@ids};
my @maxspeeds = map { $_->{ maxspeed } } @cars{@ids};

my (@ids, @owners, @colors, @maxspeeds);
while (my ($id, $car) = each(%$cars)) {
   push @ids,       $id;
   push @owners,    $car->{owner};
   push @colors,    $car->{colors};
   push @maxspeeds, $car->{maxspeeds};
}

这是一个奇怪的请求,因为通常避免并行数组,因为使用它们会导致更复杂的代码。