0

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
}

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I have a long list of variables that are passed in and I want to refer to them by name?
@jeffythedragonslayer - check out the Data::Alias module. References are better, though, IMO, because of the surprise factor.
I was just about to say I figured it out with references, I'll check out Data::Alias too.
2

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";
}

1 Comment

You should always discourage people from using $a or $b as variables, as they are reserved specifically for the sort function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.