Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re^2: if ($2) behaves differently than if (defined $2)

by radiantmatrix (Parson)
on Apr 15, 2008 at 18:09 UTC ( #680611=note: print w/replies, xml ) Need Help??

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

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
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

Replies are listed 'Best First'.
Re^3: if ($2) behaves differently than if (defined $2)
by repellent (Priest) on Apr 16, 2008 at 16:57 UTC
    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://680611]
[Corion]: Meh. I think I have now the parts down that I want from a simple Javascript frontend for single-page- applications with a aPerl backend. But it seems that all Javascript templating modules either don't support two-way binding (which would be nice) or ...
[Corion]: ... don't support server-side precompilation (which means the client has to compile all templates to Javascript themselves), or are giant frameworks that expect to do everything (which is not what I want)
[Corion]: I feel that there is a talk somewhere in there, either about the structure and parts, or how I used several parts to get a complete whole.
[Corion]: Maybe I can still find something that is compatible with handlebars.js (which has JS precompilation) but allows for two-way data binding (which is great for the UI)

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2017-03-30 07:50 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (355 votes). Check out past polls.