• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1651
  • Last Modified:

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



0
hank1
Asked:
hank1
1 Solution
 
hank1Author Commented:
I might add that if $x = 1
and $x == undef returns true, wouldn't a sub fake out a test for undef?
0
 
ozoCommented:
with ==, undef acts like 0
with eq, undef acts like ''
to test if a variable is defined, use
defined $x

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now