Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Perl strings immutable?

Tags:

string

perl

What's happening behind the scenes when I do a concatenation on a string?

my $short = 'short';
$short .= 'cake';

Is Perl effectively creating a new string, then assigning it the correct variable reference, or are Perl strings always mutable by nature?

The motivation for this question came from a discussion I had with a colleague, who said that scripting languages can utilize immutable strings.

like image 239
Zaid Avatar asked Aug 03 '10 09:08

Zaid


People also ask

Which language string is immutable?

In Java, C#, JavaScript, Python and Go, strings are immutable.

Are strings in Go immutable?

Go strings are immutable and behave like read-only byte slices (with a few extra properties). To update the data, use a rune slice instead. If the string only contains ASCII characters, you could also use a byte slice. See String functions cheat sheet for an overview of strings in Go.

Why is Golang string immutable?

Golang strings are immutable. In general, immutable data is simpler to reason about, but it also means your program must allocate more memory to “change” that data. Sometimes, your program can't afford that luxury. For example, there might not be any more memory to allocate.

Are kotlin strings immutable?

Kotlin/Java strings are immutable, which means that all modification operations create new string instead of modifying a string in-place.


2 Answers

Perl strings are mutable. Perl automatically creates new buffers, if required.

use Devel::Peek;
my $short = 'short';

Dump($short);
Dump($short .= 'cake');
Dump($short = "");

SV = PV(0x28403038) at 0x284766f4
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x28459078 "short"\0
  CUR = 5
  LEN = 8
SV = PV(0x28403038) at 0x284766f4
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x28458120 "shortcake"\0
  CUR = 9
  LEN = 12
SV = PV(0x28403038) at 0x284766f4
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x28458120 ""\0
  CUR = 0
  LEN = 12

Note that no new buffer is allocated in the third case.

like image 128
Eugene Yarmash Avatar answered Oct 16 '22 03:10

Eugene Yarmash


Perl strings are definitely mutable. Each will store an allocated buffer size in addition to the used length and beginning offset, and the buffer will be expanded as needed. (The beginning offset is useful to allow consumptive operations like s/^abc// to not have to move the actual data.)

like image 31
ysth Avatar answered Oct 16 '22 03:10

ysth