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

Hi monks -

This code does not give me what I want / would expect. Apologies for the messyness I cobbled this test script together quickly :

use strict; use Data::Dumper; sub Test { my($OldRef, $RefToRef) = @_; $RefToRef = $OldRef->{ AA }; printf STDOUT ( "-->%s<--\n-->%s<--\n", Dumper( $OldRef ), Dumper( + $RefToRef ) ); } my( $NewRef ); my( $OusideRef ) = { AA => [ 1, 2 ] }; Test($OusideRef, $NewRef); printf STDOUT ( "-->%s<--\n-->%s<--\n", Dumper( $NewRef ), Dumper( $Ou +sideRef ) );

I want this to result in $NewRef being a reference to the array in $OusideRef. I've messed around with backslashes and curley brackets etc., but I can't get it to work. I definately want to be able to create the reference within the sub, rather than outside it.

Thanks!

Replies are listed 'Best First'.
Re: Create a reference in a sub and pass it back?
by moritz (Cardinal) on Sep 16, 2009 at 11:06 UTC
    If you want to modify arguments passed to a subroutine you have to assign to $_[1] or so directly.

    However in many cases this is considered rather bad style, and needs to be documented very well.

    If you have the option, consider returning a data structure from the subroutine instead.

    Perl 6 - links to (nearly) everything that is Perl 6.

      Many thanks, works perfectly.