Darkwing has asked for the wisdom of the Perl Monks concerning the following question:
Hi community, this is my very first question here.
I have some problems with /g, \G and pos() and i do not understand what's going on (possibly a bug in my version of perl?). Hope someone knows about the following behaviour of perl:
Output:# File: defect1.pl use strict; use warnings; my $str = " xyz"; $str =~ /^(\s*)/g or die; print("match1: pos=", pos($str), "\n"); $str =~ /\G(\s*)/g or die; print("match2: pos=", pos($str), "\n"); $str =~ /\G(\s*)/g or die; print("match3: pos=", pos($str), "\n");
match1: pos=2 match2: pos=2 Died at defect1.pl line 13.
Why does the third match fail? I'd expect that after the first regex i could repeat $str=~/\G(\s*)/g again and again, it should always succeed (and never change pos()) since \s* also matches zero occurrences of spaces.
Even worse is this:Output:use strict; use warnings; my $str = " xyz"; $str =~ /^(\s*)/g; my ($x) = ($str =~ /\G(x)/g) or die; defined(pos($str)) or warn("pos() is undefined!\n"); print("this should be x:$x\n");
Even though the regex succeeded and $x has the correct value, pos($str) is undefined. Same result from this variant:pos() is undefined! this should be x:x
Again:use strict; use warnings; my $str = " xyz"; $str =~ /^(\s*)/g; my $x = ($str =~ /\G(x)/g)[0] or die; defined(pos($str)) or warn("pos() is undefined!\n"); print("this should be x:$x\n");
In contrast, the following works fine:pos() is undefined! this should be x:x
Output:use strict; use warnings; my $str = " xyz"; $str =~ /^(\s*)/g; $str =~ /\G(x)/g or die; my $x = $1; defined(pos($str)) or warn("pos() is undefined!\n"); print("this should be x:$x\n");
Obviously, perl clobbers the position associated with $str as soon as i treat the regex's result as an array - but why? I'm running perl 5.14 on Suse Linux 12.1. perl -v says:this should be x:x
This is perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-li +nux-thread-multi
Back to
Seekers of Perl Wisdom