lemming has asked for the wisdom of the Perl Monks concerning the following question:

Someone asked in the CB how to sort alphabetically, but to have all items beginning with "X" to be listed first.

My solution:
@arr = sort { ("X" eq substr($b,0,1)) <=> ("X" eq substr($a,0,1)) or $a cmp $b} @arr;

Very simplistic and note this is in ASCII order not true alpa. For that apply lc.

Replies are listed 'Best First'.
Re: A CB Sorting Question
by runrig (Abbot) on Dec 07, 2000 at 05:24 UTC
    For this I'd probably go with the 'Schwartzian Transform':
    my @arr = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, sort_key($_) ] } @arr; sub sort_key { my $str = shift; my $first = substr($str, 0, 1) eq "X" ? "0" : "1"; return $first . $str; }
    In fact, instead of creating an array ref, you could map a character onto the front of each string in the beginning, then map it off at the end, which would be more efficient memory-wise, not sure about time-wise, but that's left for you to figure out :-)
Re: A CB Sorting Question
by boo_radley (Parson) on Dec 07, 2000 at 05:13 UTC
    my @things = qw (apple Xenon banana Xircom cheese XWindows); <br>foreach (@things) {s/^X/\00/i}; <br>@oddity = sort @things;foreach (@oddity) {s/\00/X/i}; <br>print "@ +oddity";

    obviously, this won't work for things that actually have \00 in them.