in reply to small steps toward Perl literacy, temp vars and parentheses

I'd code that as

use List::Util qw[ min ]; %h = map{ $_, $h{ $_ } } min keys %h;

Which I think clarifies things a lot as well as saving a little runtime.

I also favour breaking chains over several lines as I think it makes it easier to pick out what is going on.

If I needed to keep the lowest 2 or more elements then

%h = map{ $_, $h{ $_ } } ( sort{ $a <=> $b } keys %h )[ 0 .. 2 ];

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon

Replies are listed 'Best First'.
Re^2: small steps toward Perl literacy, temp vars and parentheses
by BlaisePascal (Monk) on Jun 17, 2004 at 00:03 UTC
    Hmm, your solution for keeping the lowest 2 or more elements still puts the indexing at the end, but it changes the op structure to  %h = op4 (op2 op1 %h) op3 which from a jumping back and forth from beginning to end issue is worse. But it does change the structure in another way that suggests:
    %h = map { $_, $h{ $_ } } shift sort { $a <==> $b } keys %h;
    (that, by the way, is completely untested. Hmm, testing says it doesn't work, type of arg 1 of shift must be array, not sort. i wasn't aware that sort was a type. I wonder how to do what I want...)

      I guess we read the code in different ways. I don't think of the code as a list of operations applied to %h, but as assigning the results of map to %h.

      map takes a list and manipulates it. The fact that the input to map is also derived from %h is effectively moot. It could equally well be a completely different hash.

      I look at

      %h = map{ $_, $h{ $_ } } ( sort{ $a <=> $b } keys %h )[ 0 .. 2 ];

      as: Take the first 3 from a list of sorted keys and feed them to map. Map those keys to key/value pairs and assign them to %h.


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon