Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

binding operator

by catfish1116 (Beadle)
on Jul 21, 2020 at 15:45 UTC ( #11119607=perlquestion: print w/replies, xml ) Need Help??

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 (Archbishop) 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 (Chancellor) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11119607]
Approved by Eily
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2020-10-26 12:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (251 votes). Check out past polls.

    Notices?