in reply to sort hash keys as numbers and maybe even more...

Implementation wise, how do you do this? Do you start off with a numerical sort, then redo the sort partway through if you detect a string? Do you require that lists be marked as containing only numbers? How do you handle tied variables or objects that can numify and stringify at will?

I don't think it's easy, and that's why the second sentence of perlfunc for sort says:

If SUBNAME or BLOCK is omitted, "sort"s in standard string comparison order.
  • Comment on Re: sort hash keys as numbers and maybe even more...

Replies are listed 'Best First'.
Re: Re: sort hash keys as numbers and maybe even more...
by pg (Canon) on Feb 05, 2003 at 22:57 UTC
    I agree, it would not be easy. Not trying to argue about this, just thinking what the root cause is, other than that Perl does not support strong type.

    I am thinking the other important thing contributed to this problem, is that Perl is not really OO. Think in this way, in a OO language, like Java or c++, a list would always contain the virtually the same type of element, even though they might actually be quite different, but you can always use the sort defined on the weakest type, (in Perl, the worst would be go back to the Object class, which is the base for all).

    In a OO language, the realization of what is contained in a list, is obviously not a problem.

      Java allows you define arrays of type Object and put whatever you want into them -- good luck sorting those.
      Object fruit[] = new Object[2]; fruit[0] = new Apple(); fruit[1] = new Orange();
      I am thinking the other important thing contributed to this problem, is that Perl is not really OO.

      Surely that's a typing issue rather than an OO issue? (e.g. Eiffel & CLOS allow lists/collections of any type and are both "OO". ML types lists and isn't.)

Re: Re: sort hash keys as numbers and maybe even more...
by John M. Dlugosz (Monsignor) on Feb 07, 2003 at 20:37 UTC
    Hmm, perhaps if the value used as a key has a 'hash' property, it's used as the internal hashvalue; by default it stringifies and uses the built-in hash algorithm on the string.

    What order to sort keys in when listing them? Well, each and keys doesn't have any kind of order to it in the first place. If you want an order, use sort. The block argument to sort specifies the algorithm to use. The default ordering is string cmp, and that has nothing to do with hashes. That's just what you get if you sort keys.

    —John