Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

My favorite looping mechanism in Perl is:

by vroom (His Eminence)
on May 09, 2000 at 00:08 UTC ( [id://10659] : poll . print w/replies, xml ) Need Help??

Vote on this poll

[bar] 26/20%
[bar] 71/55%
[bar] 25/19%
[bar] 3/2%
[bar] 4/3%
129 total votes
  • Comment on My favorite looping mechanism in Perl is:
Replies are listed 'Best First'.
RE: My favorite looping mechanism in Perl is:
by merlyn (Sage) on May 09, 2000 at 16:59 UTC
    My favorite construct is the naked block, together with redo and last to trigger restart and exit:
    { blah; blah blah; last if $some_condition; more blah; more blah blah; redo if $some_other_condition; }
    There... we've got a middle-exiting loop, guaranteeing at least one execution of the first part. Who says we don't have an easy "do-while" loop!

    -- Randal L. Schwartz, Perl hacker

      This is not an original observation, but you are one sick man. ;-)

      Thanks, Randal, for the insights you have shared in actually USING perl over the years.

      We appreciate it greatly.

grep! (My favorite <em>this</em> week, anyway...)
by Russ (Deacon) on May 11, 2000 at 06:49 UTC
    Don't forget grep!

    my @True; for my $Element (@Array){ if ($Element){ push @True, $Element; } }
    my @True = grep {$_} @Array;
    To get every nth element from a list:
    (Previously posted by me as Anonymous Monk...)
    #(For every fourth element in @List) grep {not ++$i % 4} @List; #(To skip every fifth element) grep {++$i % 5} (1..50)
    I suppose we could argue that grep isn't really intended as a looping mechanism, but map seems to be popular around here, and map is implemented on grep code (internally) so...



RE: My favorite looping mechanism in Perl is:
by marcos (Scribe) on May 10, 2000 at 13:05 UTC
    I agree with BBQ: I love foreach, but when I discovered map ... it was love at first sight :) being able to write things like:
    @words = ('foo', 'bar', 'and', 'whatelse'); map {print "$_\n"} @words;

    is a real pleasure for me!
      Don't use map in a void context. Now that the backwards foreach is in there, it's never necessary. And it's also wasteful.
        Thank you for your note, but could you please explain why using map in void context is "a wasteful"? Is it a problem of code performance and/or optimization?
        TIA, marcos
      map! Map! MAP! I love it. I have never used it, and now I'm thinking of all of the extra lines of code I've written over time to do what a simple map does!!!

      Thank you!
      I think I have a new favorite widget for the week!

      Your humble servant,
        This is the same reaction I had when I discovered map :-) I'm not sure if it is a real looping mechanism (technically speaking): if you check the manpage it says "map - apply a change to a list to get back a new list with the changes". Anyway I think it is very powerful, and very beautiful, and I use whenever I can!
RE: My favorite looping mechanism in Perl is:
by Simplicus (Monk) on May 09, 2000 at 22:55 UTC
    foreach is cool, but without while you couldn't say while(<FILE>), which is cool, too...
      AHA! But you CAN! One of my 1st posts (back in December) was exactly on this topic. The only reason why its not good to do a
      foreach (<FILE>) { }
      is because the whole FH gets thrown into memory before the iterations (or so I've been told). But, yeah, practically it wouldn't be that good...
RE: My favorite looping mechanism in Perl is:
by turnstep (Parson) on May 11, 2000 at 20:49 UTC

    My favorite is -p


    (Yes, it's technically a "while", but a very smooth and subtle "while"...)

by Adam (Vicar) on May 09, 2000 at 00:22 UTC
    for and foreach are synonymous. You can use either to do the same thing.
      Yeah, but foreach is so much more cuddly! Don't you just want to hug it and never let go? I could never go back to for.
        You're scaring me, John. :)
      Well, 'for' and 'foreach' may be the same, but I never use them for it. I use 'foreach' to step through arrays/lists, and I use a 'for' for pattern switching:
      for ($var) { /test/i && do { # stuff here last; }; do { # nice default last; # not really needed here .. But what the hey :) }; }
      You can lable it SWITCH and say last SWITCH .. You can even use 'break' instead of 'last' (If I remember right) .. Either way, it works like the C/C++ switch with better matching abilities :) 'foreach' and 'while' do all my loops and walk throughs. 'map' and 'grep' are used for quickly one liners, or two, depening on what I want done ...

      The right function for the job. I just don't have use for the formal 'for' loop. Too many things are far better and faster in Perl. Leave 'for(;;;)' for C(++)?, Pascal and (Q|R|V)?Basic.;P

      -- philip
      Never underestimate the power of very stupid people in large groups.

RE: My favorite looping mechanism in Perl is:
by Punto (Scribe) on May 17, 2000 at 14:42 UTC
    Well, I come from Pascal, so I don't use those fancy loop things like "foreach", or "map".

    If I want to go through an array I do:

    for ($i = 0; $i<=$#array; $i++) { stuff; };
    I also don't use $_ to get the contents of a file. I do this:
    while ($line = <FILE>) { stuff; };
    And I put ; at the end of every line..

      Personally, I find for-as-foreach more useful:

      for my $i(0..$#array) { #same thing as your C-like for stuff; }

      --Brent Dax

      @HPAJ=split("", "rekcaH lreP rentonA tsuJ"); print reverse @HPAJ; #sucky but who cares?
        Personally, I find for-as-foreach more useful:

        Try make:

        for my $i (0 .. $#array) { ... }
        efficiently do something like:
        for ($i=0; $i < @array; $i += ROWSIZE) { ... }

Re: My favorite looping mechanism in Perl is:
by ambrus (Abbot) on Aug 28, 2009 at 12:21 UTC

    Wait, I've not replied to this yet? Anyway, lots of options seem to be missing. Here are some more possibilities, no doubt there are more.

    • recursion with named subs: $_=0;sub f{say;$_++<9and f()}f;
    • recursion with subrefs: my$s;$s=sub{say$_[0];$_[0]<9and&$s(1+$_[0])};&$s(0);$s=0;
    • recursion via overload, tie, DESTROY, DB, SIG, or other automagical sub calls: $_=0;DESTROY{say$_;$_++<9and bless[]};bless[];
    • bounded looping without recursion: $_=0;sub f0{say;$_++<9}eval join"",map{"sub f".(1+$_)."{f$_ and f$_}"}0..7;f8();
    • recursion the nice way (ie. without circular references ie. without letrec or mutable variables): my$s=sub{say$_[0];$_[0]<9and&{$_[1]}(1+$_[0],$_[1])};&$s(0,$s);
    • redo: $_=0;{say;$_++<9and redo};
    • map: map say,0..9;
    • grep: grep say,0..9;
    • sort: ()=sort{$u{$a}++or say$a;$u{$b}++or say$b;0}0..9;
    • repeated substitution: $k=0;$_="a"x10;s/./say$k++/ge;
    • (?:{}) with list context g regex or the regex engine itself looping: $k=0;()=("a"x10)=~/.(?{say$k++})/g;
    • string eval: $_=0;eval "say(\$_++);"x10; (don't laugh, I heared the developers of the J programming language used this in the very early stage of creating J when it didn't yet have the goto or other control statements)
    • own loop library implemented in XS

    Update 2010-10-17: see also the other poll If I was forced to use only one kind of loop for the rest of my days it would be a.

RE: My favorite looping mechanism in Perl is:
by Grok (Initiate) on May 12, 2000 at 18:37 UTC
    What about map?
      Perhaps because map is not a looping mechanism in that you cannot break out of it by satisfying a test or by using 'last'. Technically, "goto" and "what?" are not really looping mechanisms either, and "for" and "foreach" are the same, which leaves only "while" and "for". Of course, we could add "anonymous" loops (blocks) as well, which don't have a test but can use last/next/redo. Maybe we could stretch things a bit and have a fourth entry of "do/while"...

View List Of Past Polls