Reputation: 3835
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
}
Upvotes: 0
Views: 1054
Reputation: 3835
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";
}
Upvotes: 2
Reputation: 22254
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.
Upvotes: 3