in reply to Return Value in Subroutine

test's $value and MAIN's $value are completly different variables despite the similarity in their names. Assigning to one will not change the other.

Fortunately, since parameters are passed by reference in Perl, you can change a variable in the caller by modifying the parameter ($_[0]) as opposed to a copy of it ($value).

sub test { $_[0] = "new value"; } { my $var = "old value"; print("$var\n"); test($var); print("$var\n"); }

If you wanted to use a meaningful name instead of $_[0], you could create an alias using Data::Alias or as follows:

sub test { # alias my $arg = $_[0]; our $arg; local *arg = \$_[0]; $arg = "new value"; } { my $var = "old value"; print("$var\n"); test($var); print("$var\n"); }

Update: Added aliasing bit.

Replies are listed 'Best First'.
Re^2: Return Value in Subroutine
by citromatik (Curate) on Jul 16, 2007 at 16:59 UTC

    Or maybe pass a reference in the first place (making more obvious that you expect $var to be changed):

    sub test { my ($val) = @_; $$val = "new_value"; } { my $var = "old value"; print("$var\n"); test(\$var); print("$var\n"); }