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

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Use whichever one most clearly conveys the meaning and intention of the loop in question. I use map for transforming one list to another list. I use grep for filtering items out of a list to produce a new list. I use for to iterate over a list for basically any other reason.

Do not concern yourself with the performance of a looping construct (or anything else) until you've determined that performance is a problem and you've profiled the code and found a particular loop to be the source of the performance problem. Before that, you're making your code more obscure in order to solve a problem that might not even be there.

It's a rare loop whose execution time is influenced by the method of iteration. Look at the examples in this thread. To see differences between map and for, monks are writing loops that do naught more than simple addition. Consider this loop instead:

for my $ip ( @accessors ) { system( 'host', $ip ) == 0 or die "system(host) failed: $?"; }

Would that be faster or slower with map or grep? I doubt it. The call to system is likely taking nearly all of the time, and most of that time is spent waiting on the name server being queried by the 'host' command. Converting this to some other looping construct would have a much greater effect on comprehensibility than on its execution speed and often times clear code is more valuable than fast code anyway.

In reply to Re: Map Vs Foreach by kyle
in thread Map Vs Foreach by perlCrazy

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2021-09-18 05:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found