----- Original Message ----- From: ""Wagner, David --- Senior Programmer Analyst --- WGO"" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <beginners@perl.org>
Sent: Tuesday, August 14, 2007 1:06 PM
Subject: Ability to do numeric and alpha sort in one pass on data which is compirsed of both


I am attempting to sort data which has  a combination of both numeric
and alpah numeric data. Now it would not be so bad, but the numeric data
can be either 9 or 10 characters in length and no leading zero is
supplied in the numbers.

I have supplied some code I am playing with, but running into a mental
block in attempting to get it sorted.

Any thoughts on how to approach would be greatly appreciated?
Running on XP AS 5.8.8.Build 820. Trying to use core Perl verses adding
any modules if possible.


[snip code]

Hello Wags,
I approached the problem by creating a sortstring stored as the value in the hash. By normalizing the input (to have a leading zero if there is only 9 digits), an ascii compare (cmp) can be used on all the data, whether all digits, or alphanumerical. The code for this is in the middle of the file read loop and the output code now does a standard cmp on the values of the hash.

Chris


#!/usr/bin/perl
use strict;
use warnings;

my %MPI = ();
my $MyProInfo = \%MPI;

my $MyIn = 0;
my $MyOut = 0;

my $MyWrkKey;
while ( <DATA> ) {
   chomp;
   $MyIn++;
   next if ( /^\s*(#|$)/ );
   next if ( /^\s/ );
   $MyWrkKey = substr($_,0,13);
   my $sortstr;
   if (index($_, ' ') == 9) { # (that's a space in the quotation marks)
    $sortstr = substr $_, 0, 9;
    $sortstr = '0' . $sortstr unless $sortstr =~ /\D/;
   }
   else {
    $sortstr = substr $_, 0, 10;
   }
   $MyProInfo->{$MyWrkKey} = $sortstr;
   $MyOut++;
}


foreach my $MyPrtKey (sort {$MyProInfo->{$a} cmp $MyProInfo->{$b}} keys %$MyProInfo) {
   printf "MyPrtKey: %s\n", $MyPrtKey;
}



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to