in reply to if ($2) behaves differently than if (defined $2)

From perldoc -f defined:

' Note: Many folks tend to overuse "defined", and then are surprised to discover that the number 0 and "" (the zero-length string) are, in fact, defined values.'


s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}

Replies are listed 'Best First'.
Re^2: if ($2) behaves differently than if (defined $2)
by radiantmatrix (Parson) on Apr 15, 2008 at 18:09 UTC

    That's a choice quote. Put another way, the OP is suffering from some confusion that if (defined $x) is intended to be the same as if ($x). In fact, they serve different purposes.

    defined tests whether a variable has any value -- a false value is still a value.

    Short demonstration code:

    my $x; demonstrate(); $x = 1; demonstrate(); $x = 0; demonstrate(); sub demonstrate { if (defined $x) { print "\$x has value $x\n"; } else { print "\$x is undefined\n"; } if ($x) { print "\$x evaluates as TRUE\n"; } else { print "\$x evaluates as FALSE\n"; } print "\n"; }

    This produces the following output:

    $x is undefined $x evaluates as FALSE $x has value 1 $x evaluates as TRUE $x has value 0 $x evaluates as FALSE
    <radiant.matrix>
    Ramblings and references
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet
      Apparently, in Lisp, this is referred to as a semi-predicate problem.

      The very fact that you are using
      if ($2)
      followed by
      $price = $1 . "." . $2
      shows that you are using $2 as a semi-predicate, i.e. to show validity and to hold value.

      Next time, whenever you use if ($var), you should consider if $var needs to be a full-predicate, i.e. strictly a boolean to only show true-or-false.