LPM: The times they are a-changin' (or: integer hash keys)

Joe Hourcle oneiros at dcr.net
Thu Aug 23 10:35:21 CDT 2001



On Tue, 21 Aug 2001, Gregg Casillo wrote:

> My first (and presently only) idea would be to zero-pad those numbers so
> that they are a uniform length and thus will sort correctly. So if you
> have numbers like 3, 9, 10, 22, and 105, zero-pad them: 003, 009, 010,
> 022, and 105. Use sprintf():
>
> $padded = sprintf("%03d", 23); # $padded = 023;
>
> I don't know how feasible it would be to go back and zero-pad all of
> your numbers in question though.

Assuming you're sure they're not going to be read as numbers, and only as
strings, otherwise, you have issues with programs that think they're
octal, but find 8/9 in there.

> > Any suggestions on a good way to sort hash keys by their integer values?


#####
my @array = qw(1 2 4 5 6 10 11 12 20 24 2000);

# default
print join(' ', sort                       @array), "\n";
# alpha
print join(' ', sort { $a cmp $b }         @array), "\n";
# number
print join(' ', sort { $a <=> $b }         @array), "\n";
# force to number, number sort
print join(' ', sort { ($a+0) <=> ($b+0) } @array), "\n";

#####

I get the following output:

	1 10 11 12 2 20 2000 24 4 5 6
	1 10 11 12 2 20 2000 24 4 5 6
	1 2 4 5 6 10 11 12 20 24 2000
	1 2 4 5 6 10 11 12 20 24 2000

-Joe





More information about the Lexington-pm mailing list