当我对字符串进行连接时,幕后发生了什么?
my $short = 'short'; $short .= 'cake';
Perl是否有效地创建一个新的字符串,然后分配正确的变量引用,或Perl字符串总是可变的大自然?
这个问题的动机来自于与同事的讨论,他表示脚本语言可以使用不可变字符串.
解决方法
Perl字符串是可变的.如果需要,Perl会自动创建新的缓冲区.
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,pPOK) PV = 0x28458120 "shortcake"\0 CUR = 9 LEN = 12 SV = PV(0x28403038) at 0x284766f4 REFCNT = 1 FLAGS = (PADMY,pPOK) PV = 0x28458120 ""\0 CUR = 0 LEN = 12
请注意,在第三种情况下不会分配新的缓冲区.