Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: iterating through array and saving matches to new array

by Marshall (Canon)
on Apr 19, 2018 at 19:56 UTC ( [id://1213190]=note: print w/replies, xml ) Need Help??


in reply to Re: iterating through array and saving matches to new array
in thread iterating through array and saving matches to new array

To make the the "or" of all 3 arrays with unique values > 850, consider this:
#!/usr/bin/perl use strict; use warnings; my @b = 1..1000; my @c = 900..1000; my @d = 910..1000; # my @newb = grep {$_>850}(@b&&@c&&@d); ### will not work! my %seen; my @newb = map{ ($_ > 850 and !$seen{$_}++) ? $_: ()} (@b,@c,@d); print "@newb\n";
I am not sure what the intent here is.

Replies are listed 'Best First'.
Re^3: iterating through array and saving matches to new array
by AnomalousMonk (Archbishop) on Apr 19, 2018 at 21:32 UTC

    Wouldn't the code be more readable/maintainable/etc with List::Util::uniq():
        my @newb = uniq grep $_ > 850, @b, @c, @d;
    Results are the same per Test::More::is_deeply(). (In older Perls, see List::MoreUtils::uniq.)


    Give a man a fish:  <%-{-{-{-<

      Yes, actually it would be. Although I would still prefer the block form of grep.
      I show how to use map{}

      It actually took me quite a while to learn how to return "nothing" instead of "undef" from a map.

        ... how to return "nothing" instead of "undef" from a map.

        That is a bit tricky :)


        Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-24 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found