i have hash in perl below. there are:
%typemethodsmap = ( check_rep_exists => "1_abc", check_jdk_version => "2_abc", check_blocks_failed => "1_xyz", check_or_exists => "2_xyz", check_upg_exists => "3_xyz", check_sso_exists => "4_xyz" );
when hash read, keys not read defined read randomly. needs read , run through loop on hash based on ascending format of keys i.e. check_blocks_failed
, followed check_or_exists
followed check_upg_exists
, check_sso_exists
for value "1_xyz"
, "2_xyz"
, "3_xyz"
, "4_xyz"
respectively.
please let me know if body can me here?
yes. design, hash keys random order.
there's bunch of reasons - covered in perlsec
, keys
- long , short of if need preserve key ordering, need use sort
.
or slice
:
my @order = qw ( first second third ); %hash = ( second => 'a', third => 'b', first => 'c' ); print "@hash{@order}";
or:
foreach $key ( @order ) { print "$key = $hash{$key}\n"; }
arrays explicitly ordered numerically. hashes explicitly unordered (or random order).
if you're custom sorting, can use function returns -1, 0 or 1 based on value of comparison.
cmp
strings, , <=>
numbers.
notes custom sorting, might this:
use strict; use warnings; use data::dumper; %typemethodsmap = ( check_rep_exists => "1_abc", check_jdk_version => "2_abc", check_blocks_failed => "1_xyz", check_or_exists => "2_xyz", check_upg_exists => "3_xyz", check_sso_exists => "4_xyz", ); @order = qw( check_rep_exists check_jdk_version check_blocks_failed check_or_exists check_upg_exists check_sso_exists ); $count = 0; %magic_order = map { $_ => $count++ } @order; print dumper \%magic_order; sub custom_sort { return $magic_order{$a} <=> $magic_order{$b}; } foreach $key ( sort { custom_sort } keys %typemethodsmap ) { print $key,"\n"; }
although note - isn't more efficient, it's merely intended illustrate 'custom sorting'. alternatively - if you're wanting sort based on 'keys' being sorted:
sub custom_sort { ( $a_number, $a_text ) = split ('_',$a); ( $b_number, $b_text ) = split ( '_', $b ); if ( $a_number == $b_number ) { return $a_text cmp $b_text; } else { return $a_number <=> $b_number } }
this sort numerically first, , alphabetically second. (swap <=>
, cmp
if want opposite).
Comments
Post a Comment