in reply to sort mechanism

One nitpick that I'll comment on because it got me thinking (always a challenging task first thing in the morning... good lord, it's noon...):

I think the sort function you provided is only doing what you want by coincidence. When you say:

sort { ($a) <=> ($b) } keys %hash

The ()'s around $a and $b force the <=> operator to use list context. If we know that $a and $b will always be single (numeric) elements (as in this case), this will produce the correct behavior - but if they were lists, things would be different.

In list context, I believe <=> compares the two lists element by element - damn if I can find where that's documented, though. Brother monks? Anybody got a pointer?.

Disclaimer: Again, this is trivia, won't affect the code shown, and I need more coffee.

Peace,
-McD

Replies are listed 'Best First'.
Re: Re: sort mechanism
by extremely (Priest) on Apr 06, 2001 at 23:17 UTC
    No that doesn't work. The parens basically are no-ops there. a scalar is just a scalar. You would need @{$a} to explode the array.

    update (GOOD band names =)

    --
    $you = new YOU;
    honk() if $you->love(perl)

      Um... right. I don't think I was completely clear - what I was trying to point out was that <=> has different behavior when comparing lists than when comparing scalars.

      Although comparing two lists of a single scalar each is, as you said, exactly like comparing the naked scalars.

      So what have we learned?

      1. I shouldn't node before coffee, no matter what the hour.
      2. "Naked Scalars" would be a pretty good name for a rock and roll band.
      3. So would "Spaceship Operator."
      4. I still can't find where <=>'s behavior in list context is documented.
      Peace,
      -McD
        The equality operators apply scalar context to both sides. Try this out and see. Operators apply context. I don't think they often respond to it but with perl anything is possible =)
        my @a = keys %env; my @b = values %env; my @c = ( "equal", "a > b", "b > a" ); print ($c[@a<=>@b]),$/;

        No really, damn good band names... =)

        --
        $you = new YOU;
        honk() if $you->love(perl)