Link to home
Start Free TrialLog in
Avatar of hank1
hank1

asked on

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/;
}



Avatar of hank1
hank1

ASKER

I might add that if $x = 1
and $x == undef returns true, wouldn't a sub fake out a test for undef?
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial