On 8/22/07, Alexandru Maximciuc <[EMAIL PROTECTED]> wrote: > Hello, > > could someone please explain me these results: snip > print "1) ".scalar($_ =~ /$re/g)."\n"; > my @a = $_ =~ /$re/g; > print "1) ".scalar(@a)."\n"; snip > 1) 1 > 1) 12 snip
The issue is scalar vs list context and its effect on the g option. In scalar context g causes the regex to match once per call moving the start position to after the match. This lets you do things like: my $str = "12 24 48"; while ($str =~ /(\d+)/g) { print "found $1\n"; } In list context the g option causes the regex to match as many times as it can and returns the matches: my @matches = $str =~ /(\d+)/g; print "found " . @matches . " matches\n"; print "found $_\n" for @matches; see perldoc perlre and perldoc perlop for more information. from perldoc perlop The "/g" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern. In scalar context, each execution of "m//g" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the pos() function; see "pos" in perlfunc. A failed match normally resets the search position to the beginā ning of the string, but you can avoid that by adding the "/c" modifier (e.g. "m//gc"). Modifying the target string also resets the search position. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/