Control Structures

What is true?

  1. Any string is true except for "" and "0".

  2. Any number is true except for 0.

  3. Truth is always evaluated in scalar context, so for an array variable - its length is used.
Examples:

1 #!/usr/bin/perl my $n = "Dog"; # a string if ($n) { print "TRUE\n"; }else{ print "FALSE\n"; } # will print TRUE
2 #!/usr/bin/perl # Use this feature to check program input # receive a name from the user print "Please enter your name: "; my $name = <STDIN>; chomp ($name); # print it, or send error message if nothing entered if ($name) { print "Hello $name. Have a nice day!\n"; }else{ print "Please enter a valid name\n"; }
3 #!/usr/bin/perl my $k = 613 - 613;
# the number 0 if ($k) { print "TRUE\n"; }else{ print "FALSE\n"; } # will print FALSE
4 #!/usr/bin/perl my @a = (3, 6, 9, 12);
# an array if (@a) { print "TRUE\n"; }else{ print "FALSE\n"; } # will print TRUE
5 #!/usr/bin/perl my @e = ();
# an empty array if (@e) { print "TRUE\n"; }else{ print "FALSE\n"; } # will print FALSE


Table of Contents.
Previous | Next.