Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Validation: is defined whether the variable?

by breeze (Initiate)
on Aug 07, 2011 at 10:19 UTC ( [id://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

Replies are listed 'Best First'.
Re: Validation: is defined whether the variable?
by Perlbotics (Archbishop) 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'; }

      But thanks, your solution is work correct ;)
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Validation: is defined whether the variable?
by GrandFather (Saint) 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 :)
Re: Validation: is defined whether the variable?
by Anonymous Monk on Aug 07, 2011 at 10:31 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-24 23:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found