in reply to Can't understand why /g does not work as I expect

The /g modifier is working just fine, but your regex is too greedy (see perlreref). Change .* to .*?
$string = "<name=\"foo\"><anystring 1 /></name><name=\"bar\"><anystrin +g 2 /></name>"; while ($string =~ m/<name=\"(.*?)\">(.*?)<\/name>/g) { print "$1, $2\n"; } __END__ foo, <anystring 1 /> bar, <anystring 2 />
If this is XML, I recommend using a parser instead of regular expressions. It will save you a lot of trouble.

As an aside, you could avoid excessive back-whacking in your string by using a different quote character. For example, switch to single quotes. In my opinion, this makes the code easier to understand and maintain.

$string = '<name="foo"><anystring 1 /></name><name="bar"><anystring 2 +/></name>';

Similarly, in your regex, there is no need to escape ", nor is there a need to escape / if you switch to a different delimiter, such as {}

while ($string =~ m{<name="(.*?)">(.*?)</name>}g)

Replies are listed 'Best First'.
Re^2: Can't understand why /g does not work as I expect
by gnieddu (Initiate) on Mar 23, 2010 at 10:01 UTC

    Hi folks,

    thanks to all of you for your really useful help!