Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^4: Control Structures

by glwtta (Hermit)
on May 12, 2005 at 03:16 UTC ( [id://456221]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Control Structures
in thread Control Structures

Seems like a classic case of "doctor, it hurts when I do this".

I'd consider myself a mid-level Perl programmer, it's never even occured to me to try my $foo if $bar, simply because "conditional declaration" isn't a concept that makes sense to me. I understand the linked explanation, I'm just saying I would never have arrived at that construct on my own, so it seems unlikely to cause trouble for new programmers.

If people feel the need to abuse the side effects of an implementation bug in production code, well, that's not a problem with the language design.

Replies are listed 'Best First'.
Re^5: Control Structures
by perrin (Chancellor) on May 12, 2005 at 05:03 UTC
    If you think it's that obvious, you're not getting it. Here's some code that demonstrates how this can bite you:
    sub sticky { my $arg = shift; my $object = Some::Package->new() if $arg; $object ||= Other::Package->new(); }
    The first time you run it with $arg = 0, you will get the expected result. The second time through with $arg = 0, you will find the Other::Package object from last time in $object and it will not get a fresh Other::Package object assigned to it. So, if you never put anything in $object when the conditional is false, you won't actually see the bug.

    I have personally seen people lose days debugging problems caused by this, and have heard stories about it happening in other companies too. It's hard to see, it's very hard for people to fully understand, and it really happens in production code.

      I understand how the problem manifests itself, it's not rocket science after all.

      What I am saying is that if I want this:

      sub foo { my $arg = shift; my $object = ($arg) ? Some::Package->new() : Other::Package->new(); }
      It seems blindingly obvious that the snippet you provided is not the way to go about it. I agree that the compiler should warn you about this (or better yet, disallow it entirely); it just seems that if someone has trouble with this, the problem probably lies with understanding 'my', not confusing if() syntax.
        "Blindingly obvious"? Your change looks like a tiny style nudge, not the difference between working and broken. It doesn't surprise me at all that people trip on this.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-19 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found