One thing I'd like to add to juerds post is that if you pass a reference and modify it in the sub, you will in fact be modifying the actual data structure (hence reference). This may not be what you want to do. It's not a problem if you are aware of it.
#!/usr/bin/perl -w use strict; my @array = (1..10); print join(", ",@array),"\n"; sillyfunc(\@array); print join(", ",@array),"\n"; sub sillyfunc{ my $aref = shift; # multiply each element by itself. $_ *= $_ foreach @{$aref}; } __END__ Even if you don't want to modify the original data, refs are used to avoid flattening. @array1=(1,2,3); @array2=('a','b','c'); (@array1,@array2) flattened would equal (1,2,3,a,b,c); What elements belong to which array?


So in our sillyfunc, if we didn't want to actually modify the original data structure, but still wanted to pass by reference, you could make a shallow copy of the original by changing the $aref assignment to my $aref = [ @{$_[0]} ] which basically says take data referent in $_[0] and put it in a new anonymous array and stuff a reference to it in $aref.

This is fine for simple data structures, but be aware that if the ref the data structure is referencing contains more references, the original and the copy's element references will still be referencing the same things. That's why it's called a shallow copy. It only gives you a new copy of the top layer.

I hope I haven't made this sound more confusing than it is. I've referenced references 9 times here...
Let me know if you need me to clarify anything and hope this helps.

-Lee

"To be civilized is to deny one's nature."

In reply to Re: Passing references to a sub. by shotgunefx
in thread Passing references to a sub. by DigitalKitty

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.