http://qs321.pair.com?node_id=11119607

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

I have written some code 2 ways, (shown below). The firsts one without the binding operator does work. The second one, with the binding operator doesn't work.

print "Enter a string: "; chomp(my $_ = <STDIN>); if ($_ = /(a|b|x)/i) { print "Its a good match\n"; } else { print "That was not a good match\n"; } print "Enter a string: "; chomp(my $teststring = <STDIN>); if ($teststring =~ m{ /(a|b|x)/}i) { print "Its a good match\n"; } else { print "That was not a good match\n"; }

I guess I don't understand the difference between binding and non-binding reg-exps. TIA, The Catfish

Replies are listed 'Best First'.
Re: binding operator
by choroba (Cardinal) on Jul 21, 2020 at 15:50 UTC
    The regexes aren't the same:
    $ perl -wE 'say for qr/(a|b|x)/i, qr{ /(a|b|x)/}i' (?^ui:(a|b|x)) (?^ui: /(a|b|x)/)

    Moreover, $_ = /.../ not only matches against $_, but also changes its content (it sets it to the result of the match).

    Also note that my $_ is invalid since 5.24.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: binding operator
by Fletch (Bishop) on Jul 21, 2020 at 15:52 UTC

    Well for one thing your first version is assigning the result of comparing qr/(a|b|x)/i against $_ back into $_. Harmless in this case, but . . .

    For another, your second chunk is attempting to match the regex qr{ /(a|b|x)/} against $teststring which isn't what you mean either. When you use the match operator with different delimiters you don't need the extra slashes (e.g. you really meant if( $teststring =~ m{(a|b|x)}i ) {...} there).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: binding operator
by Anonymous Monk on Jul 21, 2020 at 17:58 UTC
    Also: I don't think that you can say: my $_. That's a special Perl predefined name ... which I don't recommend that you use. Use my to create a local variable-name as you did in the second case.
      $_ is a special Perl predefined name ... which I don't recommend that you use

      Your recommendations mean nothing. Using $_ is best practice, in most situations.