Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: If statement not working

by perlfan (Vicar)
on Jun 25, 2020 at 17:39 UTC ( [id://11118543]=note: print w/replies, xml ) Need Help??


in reply to If statement not working

if ($_ = (m/^[\$]\w/)) {

Solution pointed out below. This is an assignment (using =) clobbering $_ with an empty array the true/false result. An assignment of an undefined thing evaluates to false every time. Similar to if ($_ = ()) or if ($_ = undef).

Update - because I was curious:

perl -MO=Deparse,-P -e 'if($_ = (m/foo/)) { print 'hi' }' if ($_ = /foo/) { print hi $_; } -e syntax OK

A little more insight.

update 2- corrected ty

Replies are listed 'Best First'.
Re^2: If statement not working
by AnomalousMonk (Archbishop) on Jun 25, 2020 at 18:44 UTC
    This is an assignment (using =) clobbering $_ with an empty array. An assignment of an undefined ... Similar to if ($_ = ()) or if ($_ = undef).

    $_ is clobbered with the true/false result of evaluating the match of the regex against $_:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -e "print 'Enter a string and I will determine the data type: '; chomp($_ = <STDIN>); dd 'A:', $_; ;; if ($_ = (m/^[\$]\w/)) { print qq{\n'$_' is a scalar data type\n}; } dd 'B:', $_; ;; if ($_ = (m/^[\@]\w/)) { print qq{\n'$_' is an array data type\n}; } dd 'C:', $_; " Enter a string and I will determine the data type: $scalar ("A:", "\$scalar") '1' is a scalar data type ("B:", 1) ("C:", "") c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -e "print 'Enter a string and I will determine the data type: '; chomp($_ = <STDIN>); dd 'A:', $_; ;; if ($_ = (m/^[\$]\w/)) { print qq{\n'$_' is a scalar data type\n}; } dd 'B:', $_; ;; if ($_ = (m/^[\@]\w/)) { print qq{\n'$_' is an array data type\n}; } dd 'C:', $_; " Enter a string and I will determine the data type: @ra ("A:", "\@ra") ("B:", "") ("C:", "")


    Give a man a fish:  <%-{-{-{-<

      ty fixed

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11118543]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (1)
As of 2024-04-24 13:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found