in reply to check undef

When comparing a value against a constant, always write the constant to the left side like this:

if (undef = $WCkey) { ...

If you make the error you made in your original post, Perl will immediately tell you.

Also, the function for checking whether a value is undef or not is the defined function.

Update: The if (undef = $WCkey) { ... is not a typo but intended for demonstration. Perl raises a runtime error when you use

if (undef = $WCkey) { ...

instead of

if (undef == $WCkey) { ...

while it doesn't even raise a warning if you write the "comparison" the other way around:

>perl -we "if (undef = $foo) { print 'bar' }" Name "main::foo" used only once: possible typo at -e line 1. Modification of a read-only value attempted at -e line 1. >perl -we "if ($foo = undef) { print 'bar' }" Name "main::foo" used only once: possible typo at -e line 1.

So, in the spirit of building a defensive habit, write the constant to the left side of comparisons for equality.

Replies are listed 'Best First'.
Re^2: check undef
by Sun751 (Beadle) on Jun 23, 2009 at 07:32 UTC
    Sorry about my original post, Now the problem is, I know defined and how to use it but the problem here is, if those variable are "undef" do some thing else, if (defined($key)) { .... } but is there any thing like this if (undefined($key)) { .... } Any suggestion???

      You have not programmed much, have you? The perlop manpage does not hide how to invert logic expressions. See logical not for how to execute something if a condition is not true.

      For futher reading, I recommend looking at Truth Tables and potentially then Boolean Logic.