Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ${^MATCH} and the /p modifier in perl v24

Tags:

perl

The perlre says:

p

Preserve the string matched such that ${^PREMATCH} , ${^MATCH} , and ${^POSTMATCH} are available for use after matching.

In Perl 5.20 and higher this is ignored. Due to a new copy-on-write mechanism, ${^PREMATCH} , ${^MATCH} , and ${^POSTMATCH} will be available after the match regardless of the modifier.

also the perlvar

${^MATCH} This is similar to $& ($MATCH ) except that it does not incur the performance penalty associated with that variable.

In Perl v5.18 and earlier, it is only guaranteed to return a defined value when the pattern was compiled or executed with the /p modifier. In Perl v5.20, the /p modifier does nothing, so ${^MATCH} does the same thing as $MATCH .

test:

echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/g'

output: two empty lines (2x \n)

but the:

echo 'Lorem ipsum dolor sit ut dicta qui dolores.' |\
 perl -nE 'say ${^MATCH} while m/dolor/gp'

output:

dolor
dolor

My perl:

$ perl -v

This is perl 5, version 24, subversion 0 (v5.24.0) built for darwin-2level
(with 1 registered patch, see perl -V for more detail)

So in the 5.24.0 the /p modifier is still needed? Or what me missed?

like image 358
kobame Avatar asked Apr 01 '17 16:04

kobame


1 Answers

There is indeed a discrepancy between the code's behaviour and the documented behaviour. Filed a bug report as ticket RT#131087.

As a workaround, you can use use $& ($MATCH).

like image 134
ikegami Avatar answered Nov 14 '22 05:11

ikegami