Original Array: 14 11 10 13 11 New Positions: 4 1 0 3 2 Ordered Array: 10 11 11 13 14 Original Positions: 2 1 4 3 0 #### #!/usr/bin/env perl ## script to practice creating numeric orderings use strict ; use warnings ; ## we want to find the POSITION of each value after ordering my @values = ( 14 , 11 , 10 , 13 , 11 ) ; ## now let's do some ordering! my %orderings = order( @values ) ; ## ## print original array and positions after ordering print "\n Original Array: " ; foreach my $value ( @values ) { print sprintf( "% 4d" , $value ) ; } print "\n New Positions: " ; foreach my $ordering ( @{ $orderings{ "new_pos" } } ) { print sprintf( "% 4d" , $ordering ) ; } print "\n" ; ## ## print ordered array and original positions print "\n Ordered Array: " ; foreach my $ordering ( @{ $orderings{ "orig_pos" } } ) { print sprintf( "% 4d" , $values[ $ordering ] ) ; } print "\n Original Positions: " ; foreach my $ordering ( @{ $orderings{ "orig_pos" } } ) { print sprintf( "% 4d" , $ordering ) ; } print "\n\n" ; ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## sub order { my @inarray = @_ ; ## elements of @inarray MUST be numeric foreach my $inval (@inarray) { if ( ! is_float( $inval ) ) { die "Fatal error. All elements of the \"order\" subroutine must be numeric." ; } } my @sorted = sort { $a <=> $b } @inarray ; ## make backups my @inarray_bkp = @inarray ; my @sorted_bkp = @sorted ; ## now get original and new positions -- store in hash of arrays my %orderings ; ## get the original positions for my $i (0..$#sorted) { for my $j (0..$#inarray) { if ( $sorted[$i] eq $inarray[$j] ) { ## return the original position push( @{ $orderings{ "orig_pos" } } , $j ) ; ## disqualify as future candidates $sorted[$i] = "AA" ; $inarray[$j] = "ZZ" ; } } } ## restore from backups @inarray = @inarray_bkp ; @sorted = @sorted_bkp ; ## get the new positions for my $i (0..$#inarray) { for my $j (0..$#sorted) { if ( $inarray[$i] eq $sorted[$j] ) { ## return the new position push( @{ $orderings{ "new_pos" } } , $j ) ; ## disqualify as future candidates $inarray[$i] = "AA" ; $sorted[$j] = "ZZ" ; } } } ## return the original and new positions return %orderings ; } sub is_float { my $inval = $_[0] ; defined $inval && $inval =~ /^[+-]?\d+(\.\d+)?$/; }