Приглашаем посетить
Html (html.find-info.ru)

Section 12.15.  Captured Values

Previous
Table of Contents
Next

12.15. Captured Values

Use the numeric capture variables only when you're sure that the preceding match succeeded.

Pattern matches that fail never assign anything to $1, $2, etc., nor do they leave those variables undefined. After an unsuccessful pattern match, the numeric capture variables remain exactly as they were before the match was attempted. Often, that means that they retain whatever values some earlier successful pattern match gave them.

So you can't test whether a pattern has matched by testing the numeric capture variables directly. A common mistake along those lines is to write something like:

    $full_name =~ m/\A (Mrs?|Ms|Dr) \s+ (\S+) \s+ (\S+) \z/xms;

    if (defined $1) {
        ($title, $first_name, $last_name) = ($1, $2, $3);
    }

The problem is that, if the match fails, $1 may still have been set by some earlier successful match in the same scope, in which case the three variables would be assigned capture values left over from that previous match.

Captured values should be used only when it's certain they actually were captured. The easiest way to ensure that is to always put capturing matches inside some kind of preliminary boolean test. For example:


    if ($full_name =~ m/\A (Mrs?|Ms|Dr) \s+ (\S+) \s+ (\S+) \z/xms) {
        ($title, $first_name, $last_name) = ($1, $2, $3);
    }

or:


    next NAME if $full_name !~ m/\A (Mrs?|Ms|Dr) \s+ (\S+) \s+ (\S+) \z/xms;

    ($title, $first_name, $last_name) = ($1, $2, $3);

    Previous
    Table of Contents
    Next