http://qs321.pair.com?node_id=172073

mt2k has asked for the wisdom of the Perl Monks concerning the following question:

Okay, I know that this subject has been talked about many times, but I am here to discuss it again!

As my example, I will use reading in data from GET and POST requests in a CGI script.
I will post four example that all produce identical output.
Then I will ask a couple of questions.

What am I asking here? Which is best for simple looping: for, foreach, grep, or map?

The Code Base

#!c:/perl/bin/perl -w use strict; use CGI; my %input; my $q = new CGI; # This is where we will insert the four test # instances. Right under this comment print "Content-type: text/html\n\n"; (my($n,$v) = each %input) { print "$n: $v<br>"; } # code changed at mt2k's request. -kudra Original: # print "$n: $v<br>"; while (my($n,$v) = each %input);

Now, look for the comment in that snippet. This is where each one of the following lines could be inserted to read in the query string and STDIN:

Example 1: map { $input{$_} = $q->param($_) } $q->param();

Example 2: grep { $input{$_} = $q->param($_) } $q->param();

Example 3: $input{$_} = $q->param($_) for $q->param();

Example 4: $input{$_} = $q->param($_) foreach $q->param();

Now, the big question. Which one of those four cases above is the most efficient? I am not looking to have "cool looking code". I want to know which one will give the best performance.

Myself, I would say that grep is unnecessary because we are not testing for anything and are not (explicitly) assiging the results to an array. Map also places its results into an array, but in this case should provide better performance than grep would.

I think the real debate I am having here is between for and foreach. It seems to me that for would do a better job, but am I assuming correctly? Also, perhaps map is a better option than either for or foreach...

Wisdom please and thank you!