Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Can I check if a loop's scope is entered for the first time? (functional approach)

by LanX (Saint)
on May 05, 2018 at 16:46 UTC ( [id://1214097]=note: print w/replies, xml ) Need Help??


in reply to Can I check if a loop's scope is entered for the first time?

FWIW this "works" somehow, but lacks the elegance of the "while solution" approach...

Please note that now, one can have more than just one loop var, like a "pointy block" in Perl6.

The cheat is that $a has to be global here to work under strict.*

Using my $a wouldn't work, because the scope only starts after the statements semicolon, and the body-sub is defined before.

use strict; use warnings; use Data::Dump qw/pp dd/; sub iter (&$;@) { my $gen = shift; my $body = pop; for (my $it = $gen->(@_) ; $it->(@_); ) { $body->(); } } for my $limit (reverse 1..5) { iter { countdown($limit) } $a => sub { print "$a: "; }; print "\n"; } sub countdown{ my $val = shift; my $it = sub { if ($val--) { $_[0]=$val; return 1; } return; # stop iteration }; return $it; }
4: 3: 2: 1: 0: 3: 2: 1: 0: 2: 1: 0: 1: 0: 0:

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Wikisyntax for the Monastery

update

Renamed loop to iter ... the loop construct in Perl6 is another beast, and wanted to avoid confusion.

*) remember $a and $b are global to allow sort to work.

  • Comment on Re: Can I check if a loop's scope is entered for the first time? (functional approach)
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1214097]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-24 22:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found