Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: small steps toward Perl literacy, temp vars and parentheses

by BrowserUk (Patriarch)
on Jun 16, 2004 at 22:27 UTC ( [id://367462]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://367462]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-24 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found