Perl-Sensitive Sunglasses PerlMonks

Re: Dictionary-style sort a la Tcl?

by moodster (Hermit)
 on Apr 18, 2002 at 10:35 UTC ( #160166=note: print w/replies, xml ) Need Help??

in reply to Dictionary-style sort a la Tcl?

As an exercise, I wrote a new comparison routine for use with sort. It splits each string to be compared into parts and if two parts are both numbers, they will be compared numerically. Whitespace is ignored. A shorter string is considered smaller than a longer (that is, "abc" is smaller than "abcde" ).
```sub dictcmp
{
my \$ac = \$a;
my \$bc = \$b;
while( 1 ) {
my @a = \$ac =~ /^\s*(([A-Za-z]+)|(\d+))(.*)/;
my @b = \$bc =~ /^\s*(([A-Za-z]+)|(\d+))(.*)/;
return 0 if !defined \$a[0] & !defined \$b[0];
return -1 if !defined \$a[0];
return 1 if !defined \$b[0];
my \$res;
if( \$a[0] =~ /\d+/ && \$b[0] =~ /\d+/) {
\$res = \$a[0] <=> \$b[0];
}
else {
\$res = \$a[0] cmp \$b[0];
}
return \$res if \$res;
\$ac = \$a[3];
\$bc = \$b[3];
}
}
Calling this routine optimized would be a blatant lie, and I'm sure a lot of things can be improved. It does work, however, at least for simple input data:
```my @list = ( "x10 y", "1abc", "a10y", "x9y", " b1" );
print join "\n", sort dictcmp @list;
yields
```1abc
a10y
b1
x9y
x10 y

Cheers,
--Moodster

Create A New User
Node Status?
node history
Node Type: note [id://160166]
help
Chatterbox?
 [erix]: (you're welcome :P) [james28909]: you know, i had a thought a few mnths back. what if this universe were just a puzzle, waiting for life to figure it out! [james28909]: what if one day we are able to grab the curtain that is "spacetime" and pull it back to reveal pulling at levers and ropes xD [holli]: like dorothy? [james28909]: see ya later holli [james28909]: yeah like wizard of oz lol. its just a joke though [james28909]: i cannot understand how someone cant see that a cloud of gas that evolves into a solar system or galaxies. it just makes sense to me. everythign that has happened, had to have happened for anything on this planet to be. [james28909]: /gas/gas and debris/ [james28909]: another thing, i used to be atheist. life experiences, personal evidence. and my own perception is the reason why i believe the things i do.

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (13)
As of 2017-12-15 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What programming language do you hate the most?

Results (433 votes). Check out past polls.

Notices?