in reply to how to "rename" a global argument in subroutine?
A subroutine in Perl takes its parameters and flattens them into a single list, and implicitly puts them in an array called @_. $_[N] is the Nth element of the @_ parameters array.
The following simply assigns those elements to names:
sub do_something { my ($red, $yellow, $blue) = @_; ... }
To do what you want, you'll need to pass by reference, dereference the items within the sub and then act on them:
my ($red, $blue, $green) = qw(1 1 1); sub do_something { my ($red, $blue, $green) = @_; $$red += 1; $$green += 30; } do_something(\$red, \$blue, \$green); print "$red, $blue, $green\n";
It may be easier for you to define a single hash with all of your globals instead of individual scalars, and just pass that around via reference:
my %hash = ( red => 1, blue => 1, green => 1, ); sub do_something { my $href = shift; $href->{red} += 1; $href->{green} += 30; } do_something(\%hash); print "$hash{red}, $hash{blue}, $hash{green}\n";
Note that the longer the script gets, the harder it is to keep track of globals, especially when they get modified at-a-distance unexpectedly.
-stevieb
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: how to "rename" a global argument in subroutine?
by Anonymous Monk on Aug 11, 2015 at 18:46 UTC |