mirror of
https://github.com/Perl/perl5.git
synced 2026-01-27 01:44:43 +00:00
This commit adds OP_SUBSTR_LEFT and associated machinery for fast
handling of the constructions:
substr EXPR,0,LENGTH,''
and
substr EXPR,0,LENGTH
Where EXPR is a scalar lexical, the OFFSET is zero, and either there
is no REPLACEMENT or it is the empty string. LENGTH can be anything
that OP_SUBSTR supports. These constraints allow for a very stripped
back and optimised version of pp_substr.
The primary motivation was for situations where a scalar, containing
some network packets or other binary data structure, is being parsed
piecemeal. Nibbling away at the scalar can be useful when you don't
know how exactly it will be parsed and unpacked until you get started.
It also means that you don't need to worry about correctly updating
a separate offset variable.
This operator also turns out to be an efficient way to (destructively)
break an expression up into fixed size chunks. For example, given:
my $x = ''; my $str = "A"x100_000_000;
This code:
$x = substr($str, 0, 5, "") while ($str);
is twice as fast as doing:
for ($pos = 0; $pos < length($str); $pos += 5) {
$x = substr($str, $pos, 5);
}
Compared with blead, `$y = substr($x, 0, 5)` runs 40% faster and
`$y = substr($x, 0, 5, '')` runs 45% faster.