On 3/7/06, Gavin Bowlby <[EMAIL PROTECTED]> wrote:
> So
>
> (\.)?
>
> differs from
>
> (\.?)
>
> in that there is no match in the first case, but there is a match in the
> second case?

Well, to be sure, we're talking about a successful pattern match in
either case. But the first one has a quantifier applied to memory
parentheses, and the result of that isn't easy to intuit.

Quantifiers, such as *, ?, and +, indicate that the preceding item is
repeated a certain number of times. They are the "loops" we use in
programming the regular expression engine. But if memory parentheses
are involved, which iteration of the quantifier gets remembered? It's
the last iteration, generally. (There are complexities. Curious folks
should see the perl docs and Friedl's "Mastering Regular
Expressions".) But if the key part of the pattern is matched zero
times, as the ? allows, there's no value for the corresponding memory
variable, so it gets undef.

The moral of the story is: Don't use quantifiers on memory
parentheses. It will probably confuse the next programmer. :-)

But it's good to be prepared for memory variables to be undefined,
even after a successful match, if the pattern allows for them to be
skipped.

> I'm still confused as to why the placement of the ? operator inside or
> outside the parentheses makes a difference.
>
> I thought the parentheses were only there to bind the result to a $N
> variable, not to change the operations of the pattern matching itself.

Ah, parentheses in pattern matches have two functions: They group
items together, as in mathematics; and they activate the regular
expression engine's memory. If you wish only grouping, Perl's patterns
also offer non-memory parentheses. But ordinary parentheses do both
jobs.

Another way to think about it: (\.)? is "an optional memory (of a
dot)", while (\.?) is "a memory of an optional dot".

Cheers!

--Tom Phoenix
Stonehenge Perl Training

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to