|
|
Question : perl school; undef, legit use of
|
|
I often test subs for an undef returns (return undef). Is it legal to test scalars $x == undef? It seems that only a test against an explictly assigned value of 'undef' is meaningful.
If not, ignor the rest of the question.
==============================================
Here a program where I test every state of $x I could think of. Here's the output: Is nothing undefined: yes Is an unassigned declaraton undefined: yes # $x; Is an undefed var undefined: yes # undef $x; Is a string var undefined: yes # $x = "sdfsdfsdfsdf"; Is a one var undefined: no # $x = 1; Is var assigned to undef, undefined: yes # $x = undef; Is var assigned to !undef, undefined: no # $x = !undef;
================================== print qq/Is nothing undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
$x; print qq/Is an unassigned declaraton undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
undef $x; print qq/Is an undefed var undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
$x = "this is a string"; print qq/Is a string var undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
$x = 1; print qq/Is a one var undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
$x = undef; print qq/Is var assigned to undef, undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
$x = !undef; print qq/Is var assigned to !undef, undefined: /; if ($x == undef) { print qq/yes\n/; }else { print qq/no\n/; }
|
Answer : perl school; undef, legit use of
|
|
with ==, undef acts like 0 with eq, undef acts like '' to test if a variable is defined, use defined $x
|
|
|
|
|