in reply to Re: Help with references
in thread Help with references

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.

Replies are listed 'Best First'.
Re^3: Help with references
by sgifford (Prior) on Jul 01, 2004 at 18:54 UTC
    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.

        Garbage collection in perl is done by reference counting. By returning \@array, you are keeping a reference to @array, and thus it will not be garbage collected. You also have the advantage in that in perl, you are not dealing (directly) with memory addresses, so it's less likely that you'll shoot yourself in the foot.

        thor

        In addition to what thor says, it's important to remember that each time your code enters a block that has a my variable in it, like this sub, it creates a completely new variable (at least conceptually). So when two calls to the sub both return \@a1, they're returning completely different and unrelated variables. This is different than if \@a1 were a global variable, in which case both would return the exact same reference (and so changes to one would affect the other).

        This is one of the really nice things about Perl over languages like C, where returning a local variable from a sub is a really bad idea.