Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^4: loop array excluding some elements

by AnomalousMonk (Archbishop)
on Apr 19, 2018 at 20:58 UTC ( [id://1213193]=note: print w/replies, xml ) Need Help??


in reply to Re^3: loop array excluding some elements
in thread loop array excluding some elements

Please excuse the long delay of my reply.

I will respond to your specific points, but what prompts my reply now is my post regarding a syntactic idiom I've recently seen that perplexes me even more than the use of map under discussion here; more on that programming pearl below.

First it is one liner.

But Perl has a format-free syntax: any program can be written in one line — at least, up to the limit of the size of the compiler line input buffer. (Update: In fact, I think every modern computer language, even the P-word one, is or can be made format-free.)

... you can add logic you want under these parentheses ... on your one liner with grep you are just doing a print ...

But one can add limitless logic within the statement block (the parentheses) of a for-loop:

for (@tt) { if ($_ != 0) { do_something_with_non_zero_iterator_variable($_); do_something_else_with_it($_); } do_even_more_stuff($_); etc(); }
One could even use a meaningfully-named aliasing iterator variable:
    for my $tt_thingy (@tt) { ... }
One could even write it on a single line (please forgive any wraparound):
    for (@tt) { if ($_ != 0) { do_something_with_non_zero_iterator_variable($_); do_something_else_with_it($_); } do_even_more_stuff($_); etc(); }
So why use a map function? The only motive I can see is that one need never write a Perl-style for-loop again, but what's the advantage of that?

But as I say, the immediate prompt for this reply is the post mentioned above. As you see, this discusses the use of grep in a fashion identical to the use of map we've been talking about. Per your example code, one might write
    grep { if ($_!=0) { print "I did something when it is not zero\n"; } } @tt;
This is semantically exactly equal to the corresponding map statement and to the equivalent for-loop. While the use of map in the circumstances we've been discussing perplexes me, I'm absolutely gobsmacked by this usage of grep. Can you offer any insight into the rationale at work here? I'd be very grateful for any idea about this.


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://1213193]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-04-18 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found