Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Access a global variable from a subroutine when used as "for" iterator

by johngg (Canon)
on Dec 20, 2023 at 21:26 UTC ( [id://11156430]=note: print w/replies, xml ) Need Help??


in reply to Access a global variable from a subroutine when used as "for" iterator

You could use a subroutine reference and form a closure over $i using a do block so that it remains in scope outside the block.

johngg@aleatico:~$ perl -Mstrict -Mwarnings -E 'say q{}; my $rcShow = do { my $i = 1; sub { return $i ++ }; }; say $rcShow->() for 1 .. 3;' 1 2 3

I hope this is helpful.

Cheers,

JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2025-11-11 14:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (68 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.