It's worth noting that the special variable, "@_" contains aliases to the calling args, not copies of them. Therefore, there is no copy being made here:

sub foo { return length($_[0]); }

...because we're acting only on the aliased entity. Similarly, there should be no copy here (assuming the s/// operator doesn't make one):

sub dot_to_underscore { $_[0] =~ s/\./_/g; } my $string = 'hello.world'; print "$string\n"; dot_to_underscore($string); print "$string\n";

No copy because we acted upon the alised entity, which is the same as acting upon the entity itself. On the other hand, had we unpacked our args by assigning $string to some other variable lexically scoped to the subroutine, done a substitution (probably triggering copy on write), and then returned the string, we have the opportunity to have created at very least one copy.

Copying small strings and simple values such as integers, and even floating point numbers is pretty fast, and for general cases we probably shouldn't care. But for long strings I can see where it would be useful to be aware of what will and will not trigger a buffer copy.

On the other hand, consider this:

sub dot_to_underscore { my $string = $_[0]; # No copy on 5.20+, but yes, copy under <5.20 +. $string =~ s/\./_/; # Copy made under 5.20 because of copy-on-wri +te. return $string; # No copy under 5.20+ until the *caller* modi +fies the return string. But yes, the caller will get a copy pre-5.20. }

Dave


In reply to Re: perl string pass by value by davido
in thread perl string pass by value by pwagyi

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.