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

I have a sub very similar to:
sub my_sub{ my $handle = shift; if (handle_not_valid($handle)){ $handle = new_handle(); } ... }
My code works for anything needing the handle within the sub, but I would like to have the original handle changed as well so that the reference returned by new_handle() is available to the rest of the program--especially to the original caller of my_sub. Does that make sense? I don't have access to code where my_sub is called.

Ideas?
Thanks!

Replies are listed 'Best First'.
Re: Changing value passed to sub
by Zaxo (Archbishop) on Sep 25, 2004 at 00:18 UTC

    The elements of @_ passed to the sub are aliases to the outside values. Shifting them in to an assignment kills off the alias property. You can write,

    sub my_sub{ if (handle_not_valid($_[0])){ $_[0] = new_handle(); } # ... }
    That will change the value outside the sub if that value is modifiable. If the sub is called with an unmodifiable value, an error will result. You will probably want to handle that error.

    After Compline,
    Zaxo

Re: Changing value passed to sub
by Prior Nacre V (Hermit) on Sep 25, 2004 at 05:11 UTC

    You could use references to achieve this.

    . . . my_sub(\$handle); . . . sub my_sub{ my $handle = shift; if (handle_not_valid($$handle)){ $handle = \(new_handle()); } ... }

    Regards,

    PN5

Re: Changing value passed to sub
by johnnywang (Priest) on Sep 25, 2004 at 00:56 UTC
Re: Changing value passed to sub
by TedPride (Priest) on Sep 25, 2004 at 09:10 UTC
    I don't know how you want a new handle assigned, but the following should show you how the references are meant to be done:
    my_sub(\$handle); print $handle->[0]; sub my_sub{ my $handle = shift; if (handle_not_valid($$handle)) { $$handle = new_handle(); } } sub handle_not_valid { return !ref(shift); } sub new_handle { my @arr = (4,5,6); return \@arr; }