Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Avoiding the == blues

by TimToady (Parson)
on Dec 31, 2004 at 18:12 UTC ( [id://418568]=note: print w/replies, xml ) Need Help??


in reply to Re: Avoiding the == blues
in thread Avoiding the == blues

Yes, what's really going on here is that, while the computer treats $a == $b as commutative, the human brain is linguistically wired, and tends to parse such constructs asymmetrically as a topic and a predicate. And as it happens, the topic likes to be first. For similar reasons most OO programmers will choose to write:
foo.equals(0)
rather than:
0.equals(foo)
Despite the fact that Ruby considers 0 to be a Real Object, I suspect that even Ruby programmers will prefer the first form to the second, because that's how our brains are wired.

The solution to all this in Perl 6 will be that assignment to an existing variable in boolean context will produce a warning under strictures, but assignment to a my declaration will not. The typical use for assignment in a boolean context is actually not the if statement but the while statement:

while $item = shift(@foo) {...}
and in most cases this is probably better written as:
while my $item = shift(@foo) {...}
or even better:
for @foo -> $item {...}
Likewise,
if $x = long_expression() {...}
can turn into
given long_expression -> $x {...}
I suppose we might also allow the gcc-like workaround of putting extra parens when you want to hide the assignment from the boolean context.

Replies are listed 'Best First'.
Re^3: Avoiding the == blues
by Anonymous Monk on Jan 01, 2005 at 19:16 UTC
    Depends on the developer. It's better to write literal comparisons (literal the noun) as "bob".equals(someVariable), when there is a chance that someVariable could be null/nil/undef. Sorta the take on the if(someLiteral == someVariable) in c, so you couldn't write things like if(0=variable) by accident. Compiler err and all...
      >>"Put the constant on the left," he repeated. "You can't assign to a constant, so it's a syntax error if you say = instead of ==." Interesting, but I have to say that with practice an alarm bell goes off when I write such conditional statement anyway. In the same way that an alarm bell woulld need to go off in order to remember to put the constant on the left.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-24 04:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found