In Perl, arguments are always passed by reference

use Devel::Peek qw( Dump ); sub f { Dump( $_[0] ); # ... } my $x = "abc"; Dump( $x ); f( $x ); # Only a "C pointer" copied onto the stack.
SV = PV(0x55df7c8f0ee0) at 0x55df7c91f1e0 <-- One scalar REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x55df7c94f190 "abc"\0 CUR = 3 LEN = 16 COW_REFCNT = 1 SV = PV(0x55df7c8f0ee0) at 0x55df7c91f1e0 <-- Same scalar REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x55df7c94f190 "abc"\0 CUR = 3 LEN = 16 COW_REFCNT = 1

That said, subs typically start by making a copy of the arguments.

use Devel::Peek qw( Dump ); sub f { my $x = shift; # Scalar is copied. Dump( $x ); # ... } my $x = "abc"; Dump( $x ); f( $x ); # Only a "C pointer" copied onto the stack.
SV = PV(0x5602d6441ee0) at 0x5602d6470148 <-- One scalar REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x5602d6478030 "abc"\0 <-- String buffer CUR = 3 LEN = 16 COW_REFCNT = 1 SV = PV(0x5602d6441f00) at 0x5602d6470100 <-- Different scalar REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x5602d6478030 "abc"\0 <-- String buffer CUR = 3 LEN = 16 COW_REFCNT = 2

But notice that both scalars share the same string buffer. Since 5.20, copying a scalar containing string usually doesn't involve copying the string buffer thanks to the Copy on Write (COW) mechanism. So even when scalars are effectively passed by copy (though explicit copying), the performance cost is relatively low.


In reply to Re: Passing argument by reference (for a scalar) by ikegami
in thread Passing argument by reference (for a scalar) by jmClifford

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.