Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: map {} list or do {} for list?

by LanX (Saint)
on Apr 11, 2014 at 14:29 UTC ( [id://1081974]=note: print w/replies, xml ) Need Help??


in reply to map {} list or do {} for list?

TIMTOWTDI, both are fine.

IIRC old versions of Perl had limitations with map in void context, but that's history.

Some might argue that this is more readable

for my $key ( keys %hosts ) { if ( $hosts{$key} != $table_count ) { delete $hosts{$key}; } }

Cheers Rolf

( addicted to the Perl Programming Language)

update

inverted unless to if

update
this works
while ( my ($key,$value) = each %hosts) { delete $hosts{$key} if $value != $table_count; }

but I'm not sure about side effects!

edit

aha -> each

If you add or delete elements of a hash while you’re iterating over it, you may get entries skipped or duplicated, so don’t. Exception: It is always safe to delete the item most recently returned by "each()", which means that the following code will work:

while (($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe }

Replies are listed 'Best First'.
Re^2: map {} list or do {} for list?
by McA (Priest) on Apr 11, 2014 at 14:58 UTC
      No I didn't¹ ..

      But problem ...

      a) seems to be introduced by the new randomization, so it's a bug

      and

      b) is not new, you can't nest each %hash cause it has global side-effects². In my case it's only local to the loop.

      But yeah, I would love to have something like hashgrep and hashmap in core ...

      Cheers Rolf

      ( addicted to the Perl Programming Language)

      ¹) maybe I should switch spending time from PM to blogs.perl.org to follow Reini, Aristoteles and Damian...

      ²) maybe better phrased as "bound to the the hash ref". I can imagine situations where passing around the hashref and iterating over it in different places is useful.

        maybe I should switch spending time from PM to blogs.perl.org
        I do both. I switched from sleeping.
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^2: map {} list or do {} for list?
by McA (Priest) on Apr 11, 2014 at 14:35 UTC

    Hi Rolf,

    just wanted to post this snippet:

    for my $host (keys %hosts) { next if $hosts{$host} == $table_count; delete $hosts{$host}; }

    but checked the incomming answers before posting redundant things. In this case I had to smile because I do agree with your "taste" (++).

    UPDATE: Had an logic error in there: changed < to ==.

    McA

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-25 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found