rose has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I have few confusion is as follows. It would be very helpfull if you clear.

I have perl file name a.pl

#!/usr/local/bin/perl use b; MAIN: { my $value; b::test($value); print "\nVALUE = $value\n"; }

b.pm has following code.

package b; print "\nINSIDE-PACKAGE\n"; sub test { my ($value) = @_; $value="This is value return from sub\n"; return $value; ## If I comment this } 1;

This code is working well and the return $value also printing.

My doubt is, if I comment return $value;, the return will not print. Is there any option to print if I don't use return

Please sugget me..

Thanks!!!
Rose

Replies are listed 'Best First'.
Re: Return Value in Subroutine
by ikegami (Patriarch) on Jul 16, 2007 at 16:44 UTC

    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.

      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"); }
Re: Return Value in Subroutine
by Ploux (Acolyte) on Jul 16, 2007 at 17:41 UTC
    I don't see how your current code is working. Change this:
    b::test($value);
    to this:
    $value = b::test();
    With or without the return statement, the the last variable to be set (which is $value) will be returned.