in reply to Why does default $_ only work

Code that doesnt work:

print "Enter a string that will match the secret matching pattern \ +n"; chomp (my $selection = <STDIN>); if ($selection = (/(.)\1/)) { print "The match was perfect \n"; } else { print "Match not found \n"; }

Replies are listed 'Best First'.
Re^2: Why does default $_ only work
by BillKSmith (Monsignor) on Aug 10, 2020 at 19:41 UTC
    Your problem has nothing to do with chomp, but rather the syntax of the match. Refer to the section "Regexp Quote-Like Operators" in perlop.
    use strict; use warnings; my $secret = \"AA"; close STDIN; open STDIN, '<', $secret or die $!; print "Enter a string that will match the secret matching pattern \n"; chomp (my $selection = <STDIN>); if ($selection =~ m/(.)\1/) { print "The match was perfect \n"; } else { print "Match not found \n"; }

    OUTPUT:

    Enter a string that will match the secret matching pattern The match was perfect

    Note that you first example only appears to "work". It gets the right answer for the wrong reason.

    Bill
Re^2: Why does default $_ only work
by LanX (Saint) on Aug 10, 2020 at 19:39 UTC
Re^2: Why does default $_ only work
by perlfan (Parson) on Aug 10, 2020 at 19:38 UTC
    At first glance, it's appears to me as if it's working due to a side effect. chomp operates on $_ implicitly, which you are affecting in your example that works. I do not believe chomp is taking the LHS of the assignment and working with $_ like you think it is. Update - I stand corrected - You can actually chomp anything that's an lvalue, including an assignment:... in chomp. I do think it's related to you using $_ inconsistently when switching to $selection.

    For clarity you probably still want:

    my $selection = <STDIN>; chomp ($selection);
    And your regex seems incorrect, as pointed out by LanX. This may be where using $_ originally got you.
      I do not believe chomp is taking the LHS of the assignment and working with it that scalar.

      No, that's incorrect, chomp does modify its argument and the return value of the assignment my $selection = <STDIN> is the lvalue $selection, which chomp operates on. The use of chomp in this code is correct and has nothing to do with the problem, it's a = vs =~ problem.

        Yes, corrected this while you were likely replying. I should have confirmed before I sent the original guess. :) Thank you.