1

I just wanted to know what does this code do?

my $string_1 = "foo bar";
my $val = 3;

if($string_1) {  


}

basically what happen if you just use a variable inside an if statement?

thanks

Soncire
  • 309
  • 1
  • 5
  • 15

2 Answers2

4

It checks if the value of the variable is true. In Perl, everything is true but the following:

  • 0 and the string '0'
  • undef
  • () (the empty list)
  • '' (an empty string)

This is documented in perlsyn. It also works with any other kind of value. You can also put a string, a function call inside the if condition. The behavior is always the same.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • Truth is evaluated in scalar context, so the empty list as such does not exist. `()` in scalar context evaluated to plain old `undef`, which is false. (Similarly an empty array in scalar context is `0`, so false.) There is one other thing that evaluates to false which you missed off your list - objects which overload `bool` to return false. – tobyink Feb 25 '14 at 13:01
  • True. The explanation for `()` is nice, though it's not in perlsyn. I just rephrased what it says there. – simbabque Feb 25 '14 at 13:24
  • The explanation in perlsyn is actually pretty bad. See [this answer](http://stackoverflow.com/a/5655485/589924) – ikegami Feb 25 '14 at 13:38
0

this will check variable '$string' has not null value

user1244533
  • 101
  • 1
  • 4
  • 2
    There is no concept of `null` in Perl – Zaid Feb 25 '14 at 10:15
  • @Zaid - *"There is no concept of `null` in Perl"* The ASCII `NUL` or `null` is `0x00` and reference to it is made in the Perl documentation, e.g., [pack](http://perldoc.perl.org/functions/pack.html)'s `a` template is *"A string with arbitrary binary data, will be null padded."* – Kenosis Feb 25 '14 at 20:46