in reply to what is *undef* ?

You seem unclear between the difference between defined and false. This code should show you the difference.

In perl falseness includes these three miscreants only: 0 "" and undef. All else is true

UPDATE: Chipmunk did not like my evals so I have used 5 different perl idioms for if (condition){print this}else{print that}. Choices, choices. TIMTOWTDI TIMTOWODI. To avoid confusion these idioms all do exactly the same thing - test a condition and print someting if it is true and something different if it is not.

tachyon

my $a; print "my \$a;\n"; print "Undefined\n" unless defined $a; print "False\n" unless $a; $a=0; print "\nmy \$a=0;\n"; if (defined $a) { print "Defined\n"; } else { print "Undefined\n"; } if ($a) { print "True\n"; } else { print "False\n"; } $a=''; print "\nmy \$a='';\n"; print eval'(defined $a) ? "Defined\n" : "Undefined\n"'; print eval'($a) ? "True\n" : "False\n"'; $a=1; print "\nmy \$a=1;\n"; print ((defined $a) ? "Defined\n" : "Undefined\n"); print (($a) ? "True\n" : "False\n"); $a='foo';print "\nmy \$a='foo';\n"; print '',(defined $a) ? "Defined\n" : "Undefined\n"; print '',($a) ? "True\n" : "False\n"; undef $a; print "\nundef \$a;\n"; (defined $a) ? print "Defined\n" : print "Undefined\n"; ($a) ? print "True\n" : print "False\n";

This is about the only printing idiom that does not work! Sadly it is also the most elegant to my eyes.

print (defined $a) ? "Defined\n" : "Undefined\n";

This only works with a null string and comma after the print as shown above print '', (cond)? foo : bar

Replies are listed 'Best First'.
Re: Re: what is *undef* ?
by Vynce (Friar) on May 25, 2001 at 15:33 UTC

    actually, noyhcat, the problem with your elegant version is that it makes print act like a function (darn those parentheses, eh beatnik?). there are two easy solutions you don't mention:

    print ((defined $a) ? "Defined\n" : "Undefined\n");
    or
    print +(defined $a) ? "Defined\n" : "Undefined\n";
    the first uses another set of parens to pass print the right stuff. the second uses perl's mystifying unary plus. unlike some languages, where unary plus does something useless, like take the absolute value of the argument, perl's unary + serves the important function of being a non-parenthesis. this means that things like warn, print, and my_user_func won't be handed the contents of that set of parens as their sole argument list.

    isn't that something? unary + is nothing. there's nothing like it; all it does is *be* something.

    .

    update: mmm, yes, japhy smart. vynce not so smart. obvious answer is, like japhy says, to move the parens to just around defined's argument. but i'm still happy to have gotten to explain the useful use of perl's unary +.

    .
      Or use the parentheses around the argument to defined():
      print defined($a) ? "Defined\n" : "Undefined\n";
      That looks more sensical than some floating + to make things work.

      japhy -- Perl and Regex Hacker