in reply to Randomly reassign hash keys
Hello cormanaz,
Another approach could be:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash = ( "a" => 1, "b" => 2, "c" => 3, "d" => 4 ); # Export keys from the hash my @keys = keys %hash; # Export values from the hash my @values = values %hash; my %new_hash; for ( 0 .. $#keys ) { $new_hash{splice @keys, rand @keys, 1} = splice @values, rand @val +ues, 1; } print Dumper \%new_hash; __DATA__ $ perl test.pl $VAR1 = { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 };
Update:in case that someone is interested in speed simple foreach element loop is always faster. Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Benchmark::Forking qw( cmpthese ); my %hash = ( "a" => 1, "b" => 2, "c" => 3, "d" => 4 ); # Export keys from the hash my @keys = keys %hash; # Export values from the hash my @values = values %hash; my %new_hash_1; my %new_hash_2; cmpthese(100000000, { 'loop indices' => sub { for ( 0 .. $#keys ) { $new_hash_1{splice @keys, rand @keys, 1} = splice @values, ran +d @values, 1; } }, 'loop elements' => sub { for ( @keys ) { $new_hash_2{splice @keys, rand @keys, 1} = splice @values, ran +d @values, 1; } }, }); __DATA__ $ perl test.pl Rate loop indices loop elements loop indices 5211047/s -- -58% loop elements 12531328/s 140%
Hope this helps.
|
---|