How do I pass a local variable to a Perl subroutine and modify it?
use strict;
use warnings;
sub modify_a
{
# ????
}
{
my $a = 5;
modify_a($a);
print "$a\n"; # want this to print 10
}
sub modify_a {
$_[0] *= 2;
}
The elements of @_ are aliases to the values passed in, so if you modify that directly, you'll change the caller's values. This can be useful sometimes, but is generally discouraged as it is usually a surprise to the caller.
A less magical approach is to pass a reference.
use strict;
use warnings;
sub modify_a
{
my ($a_ref) = @_;
$$a_ref = 10;
}
{
my $a = 5;
modify_a(\$a);
print "$a\n";
}
$a or $b as variables, as they are reserved specifically for the sort function.