Are Perl strings immutable?

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.

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.


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.)


$short = 'short';
print \$short;

$short .= 'cake';
print \$short;

After executing this code I get "SCALAR(0x955f468)SCALAR(0x955f468)". My answer would be 'mutable'.


Need Your Help

Is it better to use List or Collection?

java list collections abstraction

I have an object that stores some data in a list. The implementation could change later, and I don't want to expose the internal implementation to the end user. However, the user must have the abil...

How to design extensible software (plugin architecture)?

language-agnostic plugins resources extensibility

I need some resources that talk about how to design your software to be extensible, i.e. so that other people can write add-ons/plug-ins that adds functionality to it.