Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: How to access a variable inside subroutine?

by jcb (Parson)
on Sep 05, 2020 at 19:44 UTC ( [id://11121385]=note: print w/replies, xml ) Need Help??


in reply to How to access a variable inside subroutine?

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 17:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found