If-Then-Else



next up previous
Next: The while statement Up: Flow Control Previous: Flow Control

If-Then-Else

The Perl if statement has the same structure as in C. Perl uses the same conjunctions and boolean operators as C: && for ``and'', || for ``or'', and ! for ``not''. One important note is that the C-style one-statement if construct cannot be used. All of the code following a Perl conditional (if, unless, while, foreach) must be enclosed in curly brackets. For instance, this C fragment:

if (error < 0)
       fprintf(stderr,"error code %d received\n",error);

becomes this Perl fragment

if ($error < 0)
{ print STDERR "error code $error received\n"; }

The Perl analogue to C's else if construct is elsif and the else keyword works as expected.

Perl has an unless statement which reverses the sense of the conditional. For instance:

unless ($#ARGV > 0)    # are there any command line arguments?
{ print "error; no arguments specified\n"; exit 1; }

Perl's ideas about truth are similar to C. In a numeric context, a zero value is considered ``false'' and anything non-zero is ``true''. An empty string is ``false'' and a string with a length of 1 or more is true. Scalar arrays and associative arrays are considered ``true'' if they have at least 1 member and ``false'' if empty. Non-existent variables, since they are always 0, are ``false''.

Note that Perl does not have a case statement because there are numerous ways to emulate it.