"John W. Krahn" <[EMAIL PROTECTED]> writes:

> $ perl -le'$data = "one two three four five six";

> $test = $data =~ /(\S+)\s+(\S+)\s+(\S+)/;
> print "Test 1: $test";

> ($test) = $data =~ /(\S+)\s+(\S+)\s+(\S+)/;
> print "Test 2: $test";

> $test = $data =~ /(\S+)\s+(\S+)\s+(\S+)/g;
> print "Test 3: $test";

> ($test) = $data =~ /(\S+)\s+(\S+)\s+(\S+)/g;
> print "Test 4: $test";

> $test = () = $data =~ /(\S+)\s+(\S+)\s+(\S+)/;
> print "Test 5: $test";
> '

> Test 1: 1
> Test 2: one
> Test 3: 1
> Test 4: four
> Test 5: 3

It took a while for "Test 4" to work in my brain.  (I don't
have Perl running to test it out -- I'm assuming this is
real output).

Programming Perl (PP) says:
PP> The /g modifier specifies global pattern matching - that is,
PP> matching as many times as possible within the string. How it
PP> behaves depends on the context. In a list context, it
PP> returns a list of all the substrings matched by all the
PP> parentheses in the regular expression. If there are no
PP> parentheses, it returns a list of all the matched strings,
PP> as if there were parentheses around the whole pattern.
PP> 
PP> In a scalar context, m//g iterates through the string,
PP> returning true each time it matches, and false when it
PP> eventually runs out of matches. (In other words, it
PP> remembers where it left off last time and restarts the
PP> search at that point. You can find the current match
PP> position of a string using the pos function - see Chapter
PP> 3.) If you modify the string in any way, the match position
PP> is reset to the beginning.

The sneaky (clever) part to me was the m//g in scalar
context.  The first time it was called (test 3) it returned
qw(one two three).  The second time it was called (on the
same string) it started where it left off and returned
qw(four five six) which is used to assign in a list context
to the LHS.  There being only one scalar in the list to
fill, it gets the first element - four.

Thanks.


-- 
Michael R. Wolf
    All mammals learn by playing!
       [EMAIL PROTECTED]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to