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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|