Pergunta

I have a hash of a hash that's set up like this:

$hash->{$val}->{$val2}

Inside of the second hash (the one that corresponds to $val2) is a list of values. I could have three lists like this:

$hash->{$val}->{1} = [1,2,3]
$hash->{$val}->{2} = [4,5,6]
$hash->{$val}->{3} = [7,8,9]

I would like to have the values of these list put into a new array, sorted in round robin order by $val2. Thus the result would look like this:

@new_arr = (1,4,7,2,5,8,3,6,9)

Does anyone know of a way in perl that I could accomplish this? Thanks!

Foi útil?

Solução

If you have CPAN access, you could install List::MoreUtils and use it:

use List::MoreUtils qw(zip);

my @new_arr = zip(@$hash->{$val}{1}, @$hash->{$val}{2}, @$hash->{$val}{3});

If the number of key/value pairs in $hash->{$val} is dynamic, unfortunately zip requires actual arrays due to prototyping (and array refs won't do). Luckily, you can get around it by forcing old-style invocation and passing in the array refs:

use List::MoreUtils qw(zip);

my @ordered_array_refs;
push @ordered_array_refs, $hash->{$val}{$_} for sort keys %{$hash->{$val}};
my @new_arr = &zip(@ordered_array_refs);     # nasty :-(

Outras dicas

List::Gen's tuples function can do this as well:

my @tuple = tuples [1..3], [4..6], [7..9];

say "@$_" for @tuple;  # 1 4 7
                       # 2 5 8
                       # 3 6 9
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top