in reply to 5.42: Does m// toss a string around?
It's pack 'P' that's making a copy of the string buffer.
While matching creates a copy of the string matched, matching uses the COW mechanism to avoid making a copy of the string buffer when possible.[1] The COW mechanism *is* being used here, so no copy is being made by matching.
However, pack 'P' forces the scalar to have a string buffer and for it to be modifiable.[2] Since you are starting with a buffer that's shared with the literal constant and the scalar associated with $& and other regex vars, this means pack 'P' forces a copy to be made.
use Config qw( %Config ); use Devel::Peek qw( Dump ); my $ptr_size = $Config{ ptrsize }; my $ptr_format = $ptr_size == 4 ? "L" : $ptr_size == 8 ? "Q" : die( "Unsupported pointer size $ptr_size\n" ); # https://perldoc.perl.org/perlapi#SvPV_force sub SvPV_force { unpack $ptr_format, pack "P", $_[0] } my $s = "abc"; Dump $s; printf "%x\n", SvPV_force( $s ); Dump $s;
SV = PV(0x57565c72fee0) at 0x57565c75e0d0 REFCNT = 1 FLAGS = (POK,IsCOW,pPOK) PV = 0x57565c761a90 "abc"\0 CUR = 3 LEN = 16 COW_REFCNT = 1 00.00.57.56.5c.78.5b.c0 SV = PV(0x57565c72fee0) at 0x57565c75e0d0 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0x57565c785bc0 "abc"\0 CUR = 3 LEN = 16
Notice how Dump showed a shared buffer (IsCOW) before pack 'P', but one that isn't shared afterwards.
You can use the following to get the address of the string buffer without forcing it to exist and to be modifiable:
use B qw( svref_2object ); # https://perldoc.perl.org/perlapi#SvPVX sub SvPVX { svref_2object( \$_[0] )->PV } my $s = "0123456789"; printf "%x\n", SvPVX( $s ) while $s =~ /\G./g;
Matching will make a copy of the string buffer if it can't use COW. Example.
From perl5420delta,
pack("p", ...) and pack("P", ...) now SvPV_force() the supplied SV unless it is read only. This will remove CoW from the SV and prevents code that writes through the generated pointer from modifying the value of other SVs that happen the share the same CoWed string buffer.
Note: this does not make pack("p",... ) safe, if the SV is magical then any writes to the buffer will likely be discarded on the next read. [GH #22380]
Update: Renamed SvPV to SvPVX for accuracy.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 5.42: Does m// toss a string around?
by Anonymous Monk on Jan 22, 2026 at 10:50 UTC | |
by ikegami (Patriarch) on Jan 22, 2026 at 13:50 UTC | |
by Anonymous Monk on Jan 29, 2026 at 23:30 UTC | |
by ikegami (Patriarch) on Jan 30, 2026 at 18:59 UTC | |
by Anonymous Monk on Jan 30, 2026 at 22:37 UTC | |
by Anonymous Monk on Jan 30, 2026 at 22:47 UTC |