Perl 字符串是不可变的吗? [英] Are Perl strings immutable?
本文介绍了Perl 字符串是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我对字符串进行连接时,幕后发生了什么?
What's happening behind the scenes when I do a concatenation on a string?
my $short = 'short';
$short .= 'cake';
Perl 是否有效地创建了一个新字符串,然后为其分配了正确的变量引用,还是 Perl 字符串本质上总是可变的?
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.
推荐答案
Perl 字符串是可变的.如果需要,Perl 会自动创建新的缓冲区.
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 字符串是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文