in reply to Help with references

Coldmiser continues to beat his head against the wall (strict, warnings... must remember strict, and warnings).

OK, my new code stands as follows:

#!/path/to/perl -w use strict; my @array1 = (0..9); my @array2 = ('a'..'l'); my (@a1, @a2) = g(\@array1, \@array2); print "\@a1 = @a1\n"; print "\@a2 = @a2\n"; sub g { print "sub g\n"; my @a1 = @{(shift)}; my @a2 = @{(shift)}; print "$_ " for @a1; print "\n"; print "$_ " for @a2; print "\n"; return (@a1, @a2); }

Anyway to make the global @a2 not empty when I'm done?

Oh, and thank you both.

Replies are listed 'Best First'.
Re^2: Help with references
by Anonymous Monk on Jul 01, 2004 at 18:10 UTC

    Instead of returning the arrays themselves, you could return references. e.g. return ([@a1],[@a2]); (BUT NOT: return (\@a1, \@a2);) Of course, then you need to be expecting references returned from the function.

    I prefer to call the function in void context (i.e. don't expect anything to be returned from it) and pass in references to the arrays you want to assign to as parameters and then have the function fill them in for you, but this is a matter of style I guess.

    Edit by BazB: add code tags and formatting.

      Why do you recommand against return(\@a1, \@a2)?
        Point taken (I think). My initial concern was that since @a1 and @a2 were "my"-ed within the function, that returning references to them might be dangerous since they go out of scope once the function returns and aren't guaranteed to stick around afterward. But perhaps this is thinking too much like C. Can you clarify these scoping issues for me?

        In any case, the main point was that the function should return references to two arrays and not the contents of the two arrays (which get lumped together) leaving the second return slot empty.