Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: My favorite looping mechanism in Perl is:

by ambrus (Abbot)
on Aug 28, 2009 at 12:21 UTC ( #791892=note: print w/replies, xml ) Need Help??

in reply to My favorite looping mechanism in Perl is:

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://791892]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (11)
As of 2017-03-28 17:07 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (336 votes). Check out past polls.