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

I'm polishing up a little code for some code I am sending to a potential employer, but I have encountered this weirdness in perl's syntax. Here is the skinny.
sub shift_sort { my %hash = (1 => { foo => bar }, 2 => { baz => bletch }); shift @{ sort( { $a <=> $b } keys (%hash)) }; # doesnt work my @foo = sort( { $a <=> $b } keys (%hash)); shift @foo; # works }
if we look at perldoc -f scalar we see I've been away from perlmonks for a few days because my rassin-frassin ISP has been offline for a week. I am aware that Dominus has posted an excellent article on list vs. scalar context, but I only have another fifteen minutes left in the lab, and I needed to get the question asked (and hopefully answered). I am totally stumped here. I fixed it using @foo, but I would really rather not. Note please that this is working code that I was cleaning up, rather than broken code I need to fix -- so its a convenience and a courtesy more than anything. But I'd ideally like to get this done by monday when its supposed to be there. :)

indebted,
brother dep.

--
Laziness, Impatience, Hubris, and Generosity.

Replies are listed 'Best First'.
(ar0n) Re: Using shift() on sort() and syntactical funniness
by ar0n (Priest) on Apr 15, 2001 at 07:44 UTC
    The reason @{ } isn't working, is because it's meant for dereferencing an arrayref. Since (sort { $a <=> $b } keys (%hash)) isn't a reference to an array, it won't work.
    return @{ [ sort { $a <=> $b } keys (%hash) ] }[0];
    should work.

    shift operates on an array, not an expression. It does this, because it removes the first element in an array, not simply return it.

    Then again, I don't see why return (sort( { $a <=> $b } keys (%hash)))[0] wouldn't work. Haven't tried it though.

    ar0n ]

        Says merlyn:
        using sort to get the minimum value is far more expensive than it needs to be.
        While that's true, I think people overestimate the cost. For small lists, say up to a thousand items, it probably doesn't make much of a difference. It's like paying seven cents for a five cent candy bar. On the one hand, you're being overcharged by 40%. But a more useful way to look at it may be that you don't care because it's only two cents.

        For another take on this, see here and here, for example.

Re: Using shift() on sort() and syntactical funniness
by Dominus (Parson) on Apr 15, 2001 at 19:43 UTC
    I don't understand why you don't just do this:
    sub minimum { my ($min) = sort ....; return $min; }