[Mastering-perl] Why doesn't this work?

EMaki fish-mastering-perl at uc.org
Fri Dec 15 14:35:01 EST 2006



(resending, I think I sent from wrong address)

Looks like an optimisation: the /g in list context is going to
exhaust the matches. In scalar or void context, /g will act as
an iterator, so pos() needs to persist and be mutable.

In the first case, there's no reason to bother with setting
pos(), so perl can avoid upgrading $_ to PVMG:

[ eric.maki ] $ perl -MDevel::Peek
$_ = "Just another Perl hacker,";
print Dump $_;
my( @foo ) = $_ =~ /(Just)/g;
print Dump $_;
__END__
SV = PV(0x661da8) at 0x660e7c
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0x6885b0 "Just another Perl hacker,"\0
CUR = 25
LEN = 26
SV = PV(0x661da8) at 0x660e7c
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0x6885b0 "Just another Perl hacker,"\0
CUR = 25
LEN = 26
[ eric.maki ] $ perl -MDevel::Peek
$_ = "Just another Perl hacker,";
print Dump $_;
/(Just)/g;
print Dump $_;
__END__
SV = PV(0x661da8) at 0x660e7c
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0x683890 "Just another Perl hacker,"\0
CUR = 25
LEN = 26
SV = PVMG(0x674e98) at 0x660e7c
REFCNT = 1
FLAGS = (SMG,POK,pPOK)
IV = 0
NV = 0
PV = 0x683890 "Just another Perl hacker,"\0
CUR = 25
LEN = 26
MAGIC = 0x6751d8
MG_VIRTUAL = &PL_vtbl_mglob
MG_TYPE = PERL_MAGIC_regex_global(g)
MG_LEN = 4

Eric

---- original message : 2006-12-15 6:12pm : Andy Armstrong ----


> From Ch1:

>

> # Doesn't actually work - the list assignment to $word seems to kill

> pos($_)

>

> $_ = "Just another Perl hacker,";

> my $pos = pos( $_ ); # same as pos()

> print "I'm at position $pos\n"; # -1

>

> my( $word ) = /(Just)/g;

> $pos = pos();

> print "[$word] ends at position $pos\n"; # 4

>

> # This works fine

>

> $_ = "Just another Perl hacker,";

> my $pos = pos( $_ ); # same as pos()

> print "I'm at position $pos\n"; # undef

> /(Just)/g;

> $pos = pos();

> print "[$1] ends at position $pos\n"; # 4

>

> Tested on 5.8.8 Ubuntu and 5.8.6 Mac OS X.

>

>



More information about the Mastering-perl mailing list