Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: perl string pass by value

by ikegami (Patriarch)
on Apr 02, 2018 at 16:55 UTC ( [id://1212184]=note: print w/replies, xml ) Need Help??


in reply to perl string pass by value

Perl always passes by reference (not by value), so calling a sub doesn't copy the arguments.

However, the standard practice is to copy the arguments into local variables (e.g. my ($x, $y) = @_;), effectively getting copy-by-value semantics.

Since 5.20, Perl uses a copy-on-write mechanism that avoids actually copying the string until required (by the string being modified), so that copy is cheap.

sub foo { my ($s) = @_; # String copied here before 5.20 $s =~ s/.//s; # String copied here since 5.20 } foo($str); # No copying here.

So,

  • It's fine to pass long strings to subs that don't modify it or copy it.
  • It's fine to pass long strings to subs that don't modify it or copies of it, as long as you have Perl 5.20+

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1212184]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2024-04-16 16:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found