This example, sorts 2 or more rows, based on the columns. The subroutine created ( arrange() ), will sort your fields, based on field number received as argument. You can apply sorts on multiple columns on your hash data. This basicly it is a substitution for a SQL query like this: SELECT * FROM TABLE ORDER BY field1, field3,field2; (and the fields can be infinite). See the example below for more clarification.
--- Begin Code ---
#!/usr/bin/perl
my (%RET,%IN);
# Declare what to sort - testing purposes only:
%IN = ( '0' => ['mystring05','someting','number','123'],
'1' => ['abracadabra','zzzzzzz','10','123'],
'2' => ['123123','abc','someone','friend'],
'3' => ['0123','george','andy','zpdsl']
);
$"=","; # separator for array.
print "Sorting using fields 1,2:\n";
%RET = arrange(\%IN,1,2);
print "@{$RET{$_}}\n" foreach (sort keys %RET);
print "Sorting using fields 2,1:\n";
%RET = arrange(\%IN,2,1);
print "@{$RET{$_}}\n" foreach (sort keys %RET);
print "Sorting using fields 0,3:\n";
%RET = arrange(\%IN,0,3);
print "@{$RET{$_}}\n" foreach (sort keys %RET);
print "Sorting using fields 0,3,1:\n";
%RET = arrange(\%IN,0,3,1);
print "@{$RET{$_}}\n" foreach (sort keys %RET);
################ Sub routines #####################
sub arrange {
# this subroutine receives as arguments:
# arg[0] = a hash reference with data
# arg[1..i] = the field number you want to sort.
# returns a hash having as keys the position ,
# and as values arrays of elements to sort.
#
# Example:
# %RETURN = arrange ($in_hashref,1,2,3,5);
# this will sort the data located in $in_hashref,
# considering fields 1,2,3,5 - in this order.
# first field is field "0" in the numerotation
my ($in,$args,@j,$j,%OUT,%TMP,%TMP2,$str,$k,$l);
$in=$_[0];
for ($j=1;$j<scalar(@_);$j++){
push @j,$_[$j];
}
foreach $k (keys %{$in}){
$str="";
foreach (@j) {
$str.=to_sortstr($in->{$k}[$_]);
}
push @{$TMP{$str}},$k;
}
$j=0;
foreach $k (sort keys %TMP) {
foreach $l (@{$TMP{$k}}) {
$OUT{$j}=[@{$in->{$l}}];
$j++;
}
}
return %OUT;
}
sub to_sortstr {
# this subroutine converts data to be easy to concatenate
# with the sorting values (each field). This is an aditional
# subroutine for the arrange() subroutine. It receives as
# argument a string to be modified for the usage of arrange()
# and returns the modified string
# usage: $out = to_sortstr ($string);
# note that this function is not actually used in the main
# body of the program.
my ($ret,$in);
if (defined($_[0])) {
$in=$_[0];
} else {
return "";
}
if ($in=~ /^\d+$/) {
$in=sprintf("%08d",$in);
} else {
return $in;
}
}
Oliver Cage is a contributor for http://ikoupon.com and http://simbiotiq.com