Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Re-use of a global match

by casiano (Pilgrim)
on Aug 01, 2007 at 09:06 UTC ( [id://629996]=note: print w/replies, xml ) Need Help??


in reply to Re-use of a global match

The reason is the "g" (global) option. The "g" option means that the next search will start where the last search succeeded. There is a counter associated with the string being searched that can be accessed using the "pos" function. The search starts from "pos($regexp)". See a modified version of your code:

#!/usr/local/bin/perl use strict; use warnings; my $regexp = 'Perl Monks'; if($regexp =~ m/^Perl Monks/gi) { print "\nFound.."; } else { print "\nNot Found.."; } print "\npos = ".pos($regexp)."\n"; if($regexp =~ m/^Perl Monks/gi) { print "\nFound.1."; } else { print "\nNot Found.1."; }

when you run the code you obtain:

$ perl /tmp/prueba.pl Found.. pos = 10
Since "pos" is now 10 the regexp will not match from that position.
Try to eliminate the "g" option the second time and the regexp will succeed.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://629996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-24 05:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found