http://www.perlmonks.org?node_id=919053

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