in reply to Passing references to a sub.

If not, then what is the point [of references]?

References are created so you can put ANYTHING in a scalar. This is very handy, as array elements, list elements and hash values can only be scalars. It's also handy to be able to point to an array when calling a sub, instead of passing the entire array.

Imagine you want a two-dimensional array - without references, it would not be possible: you can't have an array as an array element (it would be flattened in the array assignment). Fortunately, you can fit an array in a scalar using a reference, and that way you can have multi-dimensional array.

Imagine you have a machine with a gigabyte of available memory, and a single scalar that uses 600 megabytes of it. If you would pass it to a sub, and it would be copied, you'd run out of memory. Fortunately, by using a reference you can just point to it, and pass only a few bytes. The reference can be copied, but it will still point to the same data.

Please do read perlreftut and perlref. (Yeah, I know the perlreftut link is broken. Will someone PLEASE update the on-site documentation? Until then, use perldoc perlreftut)

U28geW91IGNhbiBhbGwgcm90MTMgY
W5kIHBhY2soKS4gQnV0IGRvIHlvdS
ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
geW91IHNlZSBpdD8gIC0tIEp1ZXJk

Replies are listed 'Best First'.
Re: Re: Passing references to a sub.
by particle (Vicar) on Apr 01, 2002 at 21:20 UTC