in reply to $1 trap

This is a well-known "trap", and can easily happen without creating such a sub. The problem is your assumption that a failed regular expression would somehow undefine $1. But it doesn't. The proper way of writing your sub is:
sub chg { $_ [0] =~ $_ [1] && $1 ? "yes\n" : "no\n"; }

Abigail

Replies are listed 'Best First'.
Re: Re: $1 trap
by Chady (Priest) on Aug 10, 2003 at 16:07 UTC
    sub chg { $_ [0] =~ $_ [1] && $1 ? "yes\n" : "no\n"; }

    Isn't the && $1 redundant here? or am I missing something out?


    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/

      The OP's code was actually returning "yes" if $1 contained a true value. So, the following would've returned "no":

      chg("w0rd", qr/(\d)/); # that's a zero, not capital O

      bbfu
      Black flowers blossom
      Fearless on my breath

        NO.

        This would return "yes", because the regex will match, and thus will return true, even if there is no parens in the regex.

        That's why this works:
        $_ = "something blah blah"; if (/something/) { print "Ok"; }

        He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

        Chady | http://chady.net/