in reply to weird regex problem

japhy at YAPC is still vigilant enough to find and answer your regex questions ;)

The problem is, as davorg pointed out, the /g modifier -- but I don't think he pointed it out the right way. If you match on a string in scalar context with m//g, then the next m//g match on that string (assuming you've not futzed with pos() or modified the string or such) will start looking where the last one left off. That means that this code:
$_ = "c a"; if (/a/g/ and /c/g) { ... }
Won't match, since after the "a" is matched, the next regex starts AFTER the "c". Removing the /g will make things work as expected.

japhy -- Perl and Regex Hacker

Replies are listed 'Best First'.
Re: weird regex problem
by dimmesdale (Friar) on Jun 14, 2001 at 22:10 UTC
    The right solution has been offered. . . but I'm a little puzzled:
    #THIS LINE BELOW! if ( $contents =~ /^line2-(\w*)/mo ) { print $1; # has to be changed as well } }
    Why do you use \w*? First, if all you have is 2-11, 2-12, etc., then a \d is by far better. Second, by having the * you allow this line to be matched: line2-
    I assume you do not wish that to happen, so add \d+ (unless you really need the \w).

    Also, as to Hofmator's optimization, I disagree. The /o will have NO effect, since the variable is not in the regex, but is bound to it. If it were $contents =~ /$line/ then it would be an optimization, but now it has no effect, and only muddies up the waters, so to say. Also, I would speculate that the /m is useless in this situation. The format is:
    line1: /stuff here/
    line2-2: /more stuff/
    .
    .
    .

    Therefore, I assume by what he gave us, that the information appears only at the beginning of the lines, and would not make sense to spread multiple lines; therefore taking away the /m would be better(not to mention /m doesn't optimize it, but slightly detracts from it).

    UPDATE: By the way, to optimize it further, you should add the caret to the regex; /^line1/ if I am correct in that line1 is at the beginning of the line.