This should do what you seem to be trying to do: (untested)
use strict; use warnings; sub counter { my @nums = (1..500); our $add = 0; for my $num (@nums) { $add += $num } } { our $add; say $add; }
This uses our to establish lexical aliases to a global variable "add" briefly as needed. For a small program, or within a module, this can be a useful technique, but please be careful not make gratuitous uses of global variables across larger programs.
If you need more than one counter, objects are a better approach: (also untested)
package Acme::Sample::Counter; sub new { my $class = shift; my $ob = (shift || 0); bless \$ob, $class; } sub count { my $self = shift; $$self += (shift || 1); } sub read { my $self = shift; return $$self; }
Used like so:
my $counter = new Acme::Sample::Counter (); $counter->count; # add 1 $counter->count(10); # add 10 say $counter->read;
Note however, that $counter->count(0) adds 1! Think about why this is so.
In reply to Re: How to access a variable inside subroutine?
by jcb
in thread How to access a variable inside subroutine?
by pritesh_ugrankar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |