in reply to Passing references to a sub.

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."