in reply to String equality and undef

If you follow the very good advice of using defined as the test, you might also want to switch the ordering of your if/else logic. Instead of

if (!defined $id) { # Deal with id } else { # Deal with not undef id }

you might want to consider

if (defined $id) { # Deal with a defined id } else { # Deal with an undefined id }

It's just personal aesthetics. The first form ("if not" / "else") sounds awkward to me compared to "if" / "else".

Replies are listed 'Best First'.
Re^2: String equality and undef
by kyle (Abbot) on Dec 09, 2008 at 15:42 UTC

    On the other hand, dealing with a bogus value is usually shorter than what you do with a real value, and I think a good style guideline is to keep "else" as close as possible to the condition it negates.

    if ( ! defined $id ) { die "Why is this ID not defined?" } else { # Twenty # or # more # lines }

    I like this guideline because I've too many times found myself looking at a screen of code like this:

    # blah # blah } else { return undef; } } else { unlink $tmpfile; return undef; }

    What were the conditions?

    Even better in this case would have been an early return so as to avoid the extra level of indent anyway, but that's beside the point.

      Fair point, but you don't really need to worry about the else when your reaction to the if condition is death.

      unless ( defined $id ) { die "Why is this ID not defined?"; } # Life goes on normally for everyone else.

      And I disagree with your closing, an early return in cases like that is exactly the point. You want to take any steps you can to make the code more readable, especially if it means completely ignoring my initial "switch the logic" comment.