G'day pritesh_ugrankar,

Some preamble:

Your 'use 5.030;' will give you an automatic 'use strict;' but not a 'use warnings;'. It would've been better to start with:

use 5.030; use warnings;

For the code you've posted, you only need 'use 5.010;' for state and say, see perl5100delta; and 'use 5.012;' to get the 'use strict;', see use.

In the following, I've used an alias of mine I commonly use for testing:

$ alias perle alias perle='perl -Mstrict -Mwarnings -Mautodie=:all -MCarp::Always -E +'

and, my Perl version is 5.32.0:

$ perl -v | head -2 | tail -1 This is perl 5, version 32, subversion 0 (v5.32.0) built for cygwin-th +read-multi

Here's an example of what you could have done that makes sense of the use of state (using slightly easier to follow numbers):

$ perle ' say counter() for 1..3; sub counter { state $add; $add += $_ for (1..5); return $add; } ' 15 30 45

You could've also assigned the return value and used it later. This example also shows two $add variables, used in different lexical scopes, with no conflict.

$ perle ' my $add; for (1..3) { $add = counter(); say "... other processing here ..."; say $add; } sub counter { state $add; $add += $_ for (1..5); return $add; } ' ... other processing here ... 15 ... other processing here ... 30 ... other processing here ... 45

— Ken


In reply to Re: How to access a variable inside subroutine? by kcott
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.