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

Hello oh wise monks; please pardon my n00biness. :)

I'd like to set some variables to the results of regex backreferences in an m// statement. An example is worth a thousand words:
m/^(\s)?exten => (35\d\d)[^;]+;(.*)/ &&my ($extension,$name) = ($2,$3)
like so does not work ("Can't modify logical and (&&) in scalar assignment at...").

Oddly, this works:
m/<same regex>/ && print ($2,$3);
Hopefully what I'm trying to do is clear from my snippets! Is there a way to do it? Thanks in advance!

Replies are listed 'Best First'.
Re: Set variables from m//
by ikegami (Patriarch) on Jun 24, 2009 at 01:35 UTC
    It's a precedence problem
    m/^(\s)?exten => (35\d\d)[^;]+;(.*)/ && ( my ($extension,$name) = ($2, +$3) );

    but conditionally executing a my is not allowed and makes no sense. You want

    my (undef, $extension, $name) = m/^(\s)?exten => (35\d\d)[^;]+;(.*)/;

    Better yet, get rid of the needless capture

    my ($extension, $name) = m/^(?:\s)?exten => (35\d\d)[^;]+;(.*)/;

    Why are parens being used at all?

    my ($extension, $name) = m/^\s?exten => (35\d\d)[^;]+;(.*)/;
      Ah, perfect!

      Won't the second example capture the wrong backreferences though?

      As for the parens, I guess you're right; that will just force it into an array context unnecessarily, no?

      Thanks!

        Won't the second example capture the wrong backreferences though?

        I don't see any backreferences.

        I don't see a problem. The first capture will be assigned to undef (i.e. dropped), the second will be assigned to $extension, the third will be assigned to $name.

        As for the parens, I guess you're right; that will just force it into an array context unnecessarily, no?

        I meant the parens around \s. It was like doing $z=($x)+($y); instead of $z=$x+$y;