in reply to How to access a variable inside subroutine?
ADD_COUNTER_CLOSURE: { # $add is not accessible outside of closure, but # you do the 'getter', "add" which has access to $add my $add = 0; sub counter { my @nums = (1..500); for my $num(@nums) { $add += $num } } # getter sub add { return $add; } } # $add is not accessible directly here, must use add subroutine my $add = add; print qq{$add\n}; # increment $add via closure() counter(); $add = add; print qq{$add\n};
Output:
0 125250
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to access a variable inside subroutine?
by pryrt (Abbot) on Sep 05, 2020 at 20:43 UTC | |
by Fletch (Bishop) on Sep 06, 2020 at 05:10 UTC | |
by LanX (Saint) on Sep 06, 2020 at 05:55 UTC | |
by tobyink (Canon) on Sep 06, 2020 at 09:04 UTC | |
by LanX (Saint) on Sep 06, 2020 at 09:42 UTC | |
| |
by pritesh_ugrankar (Monk) on Sep 05, 2020 at 21:08 UTC | |
by Anonymous Monk on Sep 06, 2020 at 22:37 UTC | |
by perlfan (Parson) on Sep 05, 2020 at 20:51 UTC | |
by perlfan (Parson) on Sep 05, 2020 at 21:20 UTC |