Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Validation: is defined whether the variable?

by breeze (Initiate)
on Aug 07, 2011 at 10:19 UTC ( #919053=perlquestion: print w/ replies, xml ) Need Help??
breeze has asked for the wisdom of the Perl Monks concerning the following question:

I have a code:
#!/usr/bin/perl use utf8; use warnings; use strict; my $var1; my $var2 = "0"; my $var3 = 0; my $var4 = "a"; print isDef($var1)."\n"; print isDef($var2)."\n"; print isDef($var3)."\n"; print isDef($var4)."\n"; sub isDef { if (shift) { return "true"; } else { return "false"; } }

The result of execution is:

./test.pl false false false true

The first variable is really undefined, but why second & third is undefined too?

p.s. Perl v5.14.1 built for i386-freebsd-thread-multi-64int

Comment on Validation: is defined whether the variable?
Select or Download Code
Re: Validation: is defined whether the variable?
by Perlbotics (Abbot) on Aug 07, 2011 at 10:30 UTC

    Because you do not test if the variable is defined but if it is true or false (0, undef, "").

    Maybe you had something like this in mind?

    sub isDef { return (defined shift) ? 'true' : 'false'; }

      No, I think the problem is not in this. I've found a description of the function defined:

      A simple Boolean test will not distinguish among undef, zero, the empty string, and "0" , which are all equally false.

        No, I think the problem is not in this.

        Your question was The first variable is really undefined, but why second & third is undefined too? so the problem is exactly this

      But thanks, your solution is work correct ;)
Re: Validation: is defined whether the variable?
by Anonymous Monk on Aug 07, 2011 at 10:31 UTC
Re: Validation: is defined whether the variable?
by GrandFather (Cardinal) on Aug 07, 2011 at 12:12 UTC

    Note that Perl has the built in function defined to make exactly the test you seem to want. If you replace isDef with defined the result will be as you seem to want.

    True laziness is hard work
      Um, thanks, the OP already received/accepted that answer :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://919053]
Approved by Perlbotics
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2014-08-01 00:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (256 votes), past polls