[comp.lang.perl] need help with {n} and bracketing

abe@mace.cc.purdue.edu (Vic Abell) (04/06/91)

The following Perl program:

	if ("one two three four\n" =~ /^((\w+\s+){3})/) {
		print '"', $1, "\" \"", $2, "\" \"", $3, "\" \"", $4, "\"\n";
	} else {
		print "No match!\n";
	}

produces:

	"one two three " "three " "" ""

I expected:

	"one two three " "one " "two " "three "

Can anyone help me understand why the "((\w+\s+){3})" matching and
bracketing expression didn't create four special Perl variables?
It appears that only the final match of the thrice-matched inner
part -- "(\w+\s+){3}" -- is being assigned to a special variable.

Vic Abell <abe@mace.cc.purdue.edu>

tchrist@convex.COM (Tom Christiansen) (04/06/91)

From the keyboard of abe@mace.cc.purdue.edu (Vic Abell):
:The following Perl program:
:
:	if ("one two three four\n" =~ /^((\w+\s+){3})/) {
:		print '"', $1, "\" \"", $2, "\" \"", $3, "\" \"", $4, "\"\n";
:	} else {
:		print "No match!\n";
:	}
:
:produces:
:
:	"one two three " "three " "" ""
:
:I expected:
:
:	"one two three " "one " "two " "three "
:
:Can anyone help me understand why the "((\w+\s+){3})" matching and
:bracketing expression didn't create four special Perl variables?

There are only two (paren-pairs), so you only get two variables.

--tom

worley@compass.com (Dale Worley) (04/06/91)

   From: abe@mace.cc.purdue.edu (Vic Abell)

   Can anyone help me understand why the "((\w+\s+){3})" matching and
   bracketing expression didn't create four special Perl variables?

For better or worse, because there are only two sets of parentheses
(lexically speaking), there will only be $1 and $2.  Every time the
regexp inside a pair of parentheses matches, its match is loaded into
the appropriate variable.  Thus, only the last thing to match a pair
of parentheses is available.  For example:

	(regexp)*	# $1 will be the last match of regexp

Undoing assignments to variables while backtracking is done is a bear,
but I assume that Perl does that correctly.

Dale

Dale Worley		Compass, Inc.			worley@compass.com
--
We will encourage you to develop the three great virtues of a
programmer:  laziness, impatience, and hubris.
-- Larry Wall and Randall Schwartz in "Programming Perl"