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


in reply to map, grep, for, foreach

How about even more simply and efficiently using methods provided by CGI.pm ...

my %input = CGI::Vars;

The above performs the same as your proposed code but ties your array in with that used internally within CGI.pm for the storage of CGI parameters.

Of the proposed code samples provided however, map and grep would be poor choices as, in the examples given, these are being used in a void context, the return values built and returned by these functions discarded. With regard to for and foreach, according to perlsyn, foreach is merely a synonym for for, the choice between the two representing a balance for the programmer between readability and brevity.

 

Replies are listed 'Best First'.
Re: Re: map, grep, for, foreach
by Kanji (Parson) on Jun 06, 2002 at 11:51 UTC
    How about even more simply and efficiently using methods provided by CGI.pm ...
    my %input = CGI::Vars;

    While it works, Vars was really intended for compatability with the old cgi-lib.pl library, and so such shares the same quirks, like null (\0) seperated values for any multi-valued parameters.

    Instead, I'd use CGI's Dump method...

        --k.


Just a quick note...
by Anonymous Monk on Jun 06, 2002 at 14:28 UTC
    As far as I can tell for and foreach are not the same. The do the have the same functionality but due to the internals of perl they execute differently (something to do with lookup tables I believe, but not sure :P ).

    A foreach runs far faster than for.

    I converted one of my data mangling scripts to foreach loops and the whole thing sped up 35%. Ever since I have stopped believing what they say about for and foreach being the same and only ever use foreach if there is a choice between the two.
      I'm interested in how you managed to draw that particular conclusion, since:
      for (1..3) {}
      and
      foreach (1..3) {}
      compile to the identical same optree.
      C:\>perl -MO=Deparse -e "print for (1..10);print foreach (1..10);" foreach $_ (1 .. 10) { print $_; } foreach $_ (1 .. 10) { print $_; } -e syntax OK

      OK, I'm confused. They parse identically.

      Do you mean 'C-style' for loops (for (i=1;i++;i<11))vs 'perl-style' for loops? If so, what you describe is documented in perlsyn.

      If not, what do you mean?

      A foreach runs far faster than for.

      Please post a small sample of code demonstrating this phenomenon.