Oh yes, for sure defining one named subroutine within another is almost never what you want. The following is a much clearer way to do things.

use v5.30; use strict; use warnings; { my $add = 0; sub getter { $add } sub counter { my @nums = (1..500); for my $num (@nums) { $add += $num; } } } counter(); say "getter => ", getter();

Though, just returning a value from counter() seems better practice:

use v5.30; use strict; use warnings; sub counter { my $add = 0; my @nums = (1..500); for my $num (@nums) { $add += $num; } return $add; } my $got = counter(); say "got => ", $got;

I've never been a big fan of state, there are not many patterns (if any) which can't be implemented with closed over my declarations.

The state keyword is mostly just syntactic sugar. The following are essentially the same:

{ my $foo = 123; sub myfunc { ...; } }
sub myfunc { state $foo = 123; ...; }

The latter allows you to eliminate a level of nesting. Also in the case where the value being assigned to $foo is expensive to calculate, it means you won't need to calculate it until myfunc is actually called (which might be never in some cases). If you don't care about undef/false values, you can kind of emulate that using:

{ my $foo; sub myfunc { $foo ||= 123; ...; } }

In reply to Re^7: How to access a variable inside subroutine? by tobyink
in thread How to access a variable inside subroutine? by pritesh_ugrankar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.