in reply to Regexp context with ||

Yes, somehow it does seem unavoidable that in the second case, the regex match gets coerced to return a scalar. I guess the only way to get the desired behavior on one line would be:
$a = ( "abc" =~ /a(b)c/ ) ? $1 : 'd';
which I would tend to prefer anyway, even if your second case worked the way you wanted it to.

Replies are listed 'Best First'.
Re: Re: Regexp context with ||
by JamesNC (Chaplain) on Apr 09, 2003 at 02:55 UTC
    Why not use or, and, eq, ne, lt, gt, le, ge for string operations instead?
    ($a) = "abc" =~ /a(b)c/ || 'd'; print $a; # prints 1 ($a) = "abc" =~ /a(b)c/ or 'd'; print $a; # prints 'b'
    Update: Added code that didn't post
      You might be surprised by this though:
      ($a) = "abc" =~ /a(b)c/ or 'd'; print defined $a ? "defined as $a\n" : "undef\n"; # prints "defined as + b" ($a) = "abc" =~ /a(x)c/ or 'd'; print defined $a ? "defined as $a\n" : "undef\n"; # prints "undef"
      See, your or is lower than the assignment. The assignment is happening at all times, assigning undef if the match fails.

      So, that isn't the answer either.

      Perhaps what you're looking for is:

      ($a) = "abc" =~ /a(b)c/ or $a = "d";

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.