Perl: Using /g modifier in scalar context

When used in scalar context, the /g modifier indicates a progressive match, which makes Perl start the next match on the same variable at a position just past where the last one stopped. After a failure, the match position normally resets back to the start.

Example:

[code language=”perl”]
C:\>perl
$a = "test";
($a =~ /test/g) ? print "Found!\n" : print "Missing!\n";
# Check again … the fun starts here
($a =~ /test/g) ? print "Found again!!\n" : print "Missing again!!\n";
# Check again … the fun starts here
($a =~ /test/g) ? print "Found after failure \n" : print "Missing after failure \n";
^D
Found!
Missing again!!
Found after failure
C:\>

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *