Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Perl always passes by reference. It's just that sometimes the caller passes temporary scalars.</p> <p>The first thing you have to realise is that the arguments of subs can be one and only one thing: a list of scalars.* One cannot pass arrays or hashes to them. Arrays and hashes are evaluated, returning a list of their content. That means that</p> <pre><code>f(@a) </code></pre> <p>is the same** as</p> <pre><code>f($a[0], $a[1], $a[2]) </code></pre> <p>Perl passes by reference. Specifically, Perl aliases each of the arguments to the elements of <code>@_</code>. Modifying the elements <code>@_</code> will change the scalars returned by <code>$a[0]</code>, etc. and thus will modify the elements of <code>@a</code>.</p> <p>The second thing of importance is that the key of an array or hash element determines where the element is stored in the structure. Otherwise, <code>$a[4]</code> and <code>$h{k}</code> would require looking at each element of the array or hash to find the desired value. This means that the keys aren't modifiable. Moving a value requires creating a new element with the new key and deleting the element at the old key.</p> <p>As such, whenever you get the keys of an array or hash, you get a <em>copy</em> of the keys. Fresh scalars, so to speak.</p> <p>Back to the question,</p> <pre><code>f(%h) </code></pre> <p>is the same** as</p> <pre><code>f( my $k1 = "a", $h{a}, my $k2 = "b", $h{b}, my $k2 = "c", $h{c}, ) </code></pre> <p><code>@_</code> is still aliased to the values returned by <code>%h</code>, but some of those are just temporary scalars used to hold a key. Changing those will have no lasting effect.</p> <p>&#42; &mdash; Some built-ins (e.g. <code>grep</code>) are more like flow control statements (e.g. <code>while</code>). They have their own parsing rules, and thus aren't limited to the conventional model of a sub.</p> <p>&#42;* &mdash; Prototypes can affect how the argument list is evaluated, but it will still result in a list of scalars.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload