The difference is that passing an array to a subroutine passes a copy of that array whereas a reference to an array you can dereference and get the actual array. Perhaps an example will help

#! perl -w use strict; my @array = ("0","1","2","3"); my $aref = \@array; print "Original array: ", @array, "\n"; print "Pass original array to testnonref(): "; testnonref(@array); print @array, "\n"; print "Running sub passing array reference and printing array:"; testref($aref); print @array, "\n"; sub testnonref { my @subarray = shift; $subarray[0] = "4"; } sub testref { my $one = shift; $$one[0] = "4"; }

Here I used your array and array reference (hases work the same way) and first I print out what the array looks like. Then I print out what the array looks like after passing it to the testnonref subroutine. Then I print out what it looks like after passing by reference. Hopefully the output will make it a little clearer:

Original array: 0123
Pass original array to testnonref(): 0123
Running sub passing array reference and printing array:4123

As you can see, passing by reference actually changes the value of your original array whereas just passing the array makes a copymakes a reference to your array using @_ and any changes are lost after the subroutine exits.

Update: thanks, I always assumed (incorrectly) that perl copied the array like other languages. This is why I love perlmonks... always learning better ways of doing things.


In reply to Re: Small troubles with references by MCS
in thread Small troubles with references by coldmiser

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.