nysus has asked for the wisdom of the Perl Monks concerning the following question:

It's true that the following will result to $x getting assigned to either '1' or undefined:
$x = $y =~ /^(z*)/;

But I just got through looking at some code like this:
local($x) = $y =~ /^(z*)/;

which assigns $x to the value of z*.

Two questions: How does this work? I know local variables carry over between subroutines, but why is it affecting the behavior of this one line?

My second question is more of a Perl philosophy question. The above bit of code strikes me as a bit unorthodox. It seems that backreferences should be used since they were designed for this very kind of situation. Now, as a new Perl programmer, I know "there is more than one way to do it", but are there times one should strive for the more correct way of doing things?

Replies are listed 'Best First'.
Re: Local variables assigned to pattern matches
by japhy (Canon) on Mar 30, 2001 at 10:32 UTC
    It's not local(), it's the parentheses around $x. A regex in scalar context returns a boolean value; a regex in list context returns the backreferences. And I recently fixed a bug related to regexes in list context.

    japhy -- Perl and Regex Hacker
      Thanks for getting back. Yeah, I just figured out it was the parentheses, not local (which I understand is not as good as passing references through @_.

      What about the second part of the question (which obviously doesn't apply to this particular situation now).

        The backreferences ($1, $2, ...) only last as to the end of the current scope, or to the next successful regex. Thus, it's pretty useful to keep them in another variable. Also, those variables are read-only, so if you need to extract something and modify it, you need another variable:
        while (<>) { chomp; my ($name) = /(\w+\s+\w+)/; $name =~ tr/\n\r\t\f / /s; # squish spaces push @names, $name; }


        japhy -- Perl and Regex Hacker
(bwana147) Local variables assigned to pattern matches
by bwana147 (Pilgrim) on Mar 30, 2001 at 19:08 UTC
    The parentheses around $x in
    local($x) = $y =~ /^(z*)/;
    force the list context. Try:
    local $x = $y =~ /^(z*)/;
    instead.

    --bwana147
Re (tilly) 1: Local variables assigned to pattern matches
by tilly (Archbishop) on Mar 31, 2001 at 00:40 UTC
    This is a side note since your question already has good answers.

    As the documentation for local says, your example should use my unless you are well aware of what both local and my do, and have a specific need that my does not work for.

    Using strict will catch many of the cases where local was used but my makes more sense.