in reply to substr sort ??

You could simply use @values = sort @values, since this checks the first two digits before the rest, yielding your ordering.
And if you are interested, it is also more efficient:
#!perl use strict; use warnings; use Benchmark; my @array = ( '04=critical', '02=informational', '01=unknown', '10=test', '03=warning', '08=foo', ); sub substr_num { @_ = sort { substr($a, 0, 2) <=> substr($b, 0, 2) } @array; } sub substr_str { @_ = sort { substr($a, 0, 2) cmp substr($b, 0, 2) } @array; } sub standard_str { @_ = sort { $a cmp $b } @array; } sub standard { @_ = sort @array; } timethese ( 100000, {'Numeric with Substring' => '&substr_num', 'String Cmp with Substring' => '&substr_str', 'Standard String Cmp' => '&standard_str', 'Standard' => '&standard'} );
Yields the output:
Benchmark: timing 100000 iterations of Numeric with Substring, Standar +d, Standard String Cmp, String Cmp with Substring... Numeric with Substring: 2 wallclock secs ( 2.47 usr + 0.00 sys = 2. +47 CPU) @40502.23/s (n=100000) Standard: 2 wallclock secs ( 1.59 usr + 0.00 sys = 1.59 CPU) @ 6277 +4.64/s (n=100000) Standard String Cmp: 2 wallclock secs ( 1.59 usr + 0.00 sys = 1.59 +CPU) @ 62735.26/s (n=100000) String Cmp with Substring: 2 wallclock secs ( 2.31 usr + 0.00 sys = + 2.31 CPU) @ 43233.90/s (n=100000)
And therefore the Ranking Sometimes it's as simple as it seems :).
Cheers, CombatSquirrel.

Replies are listed 'Best First'.
Re: Re: substr sort ??
by dbwiz (Curate) on Aug 22, 2003 at 14:32 UTC
    You could simply use @values = sort @values, since this checks the first two digits

    They are not exactly the same thing.

    Your method will only work if every element had the same number of digits. If you were to compare "1abc" and "10abc", it would give you the wrong order.

    perl -e '@array=(qw(1abc 10abc));@sorted=sort @array; print "@sorted\n +";' 10abc 1abc perl -e '@array=(qw(1abc 10abc)); @sorted = sort {$a<=>$b} @array; print "@sorted\n";' 1abc 10abc
      I know, but the example had zero-padded fixed-width integer identifiers, which suggested that the numbers were always fixed width. I thought about a Schwartzian transform at first (like flounder99 did in Re: substr sort ??), but decided it was overkill and due to the multiple mappings slower than the direct comparison approach. If the identifiers were integers with different numbers of digits, though, my code wouldn't work, as you pointed out.