----- Original Message ----- 
From: "Wong, Danny H." <[EMAIL PROTECTED]>
To: <perl-win32-users@listserv.ActiveState.com>
Sent: Saturday, December 17, 2005 7:04 AM
Subject: Sort question


> Hi Guys,
> I have an array of values. How can I sort these values that has
> a non numeric character [ _ ] in it? What I did was parse the numbers
> before the "_" character and then perform a number short on those value,
> but there must be an easier way?

You don't really have to do anything with them - unless you might also need
to sort based on what comes *after* the underscore. (See the second script
below.)

To perl, if they are declared as barewords, they are already numbers - so
perl will sort() them without any need to modify them. However, in so doing,
perl thoughtfully removes the '_'  ... so, with this method, you have to
replace it :-)

use strict;
use warnings;
use Scalar::Util;

my @unsorted = (55_20051202, 56_20051203, 57_20051204, 101_20051205,
                59_20051206, 10_20051207, 61_20051208, 62_20051208,
                63_20051208, 64_20051209, 65_20051209, 66_20051210,
                67_20051211, 68_20051212, 69_20051213, 70_20051214 );

for(@unsorted) {
   if(!Scalar::Util::looks_like_number($_))
     {die "Ooops ... $_ is not a number"}
   }

my @sorted = sort {$a <=> $b} @unsorted;

for(@sorted) {substr($_, -8, 0, '_')}

for(@sorted) {print $_, "\n"}
__END__

But, if you're simply sorting based on the value before the underscore you
could do this:

use strict;
use warnings;

# Declare the array elements as strings.
# Scalar::Utils::looks_like_number() will
# now regard them as *not* numbers. But
# sort() still seems to get it right. Perl sorts
# based solely on the numeric value that precedes
# the underscore - and simply ignores the rest.

my @unsorted = qw(55_20051202 56_20051203 57_20051204 101_20051205
                59_20051206 10_20051207 61_20051208 62_20051208
                63_20051208 64_20051209 65_20051209 66_20051210
                67_20051211 68_20051212 69_20051213 70_20051214);

no warnings("numeric"); # Avoid "isn't numeric" warnings.

my @sorted = sort {$a <=> $b} @unsorted;

for(@sorted) {print $_, "\n"}

__END__

Cheers,
Rob


_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to