Wordsmyth's Corner

Perl Primer - Chapter 3 -

by Linda Naughton

Topics
Previous Chapter Next Chapter


Operators

Standard C-style operators (including ++, +=, &&, etc.)
Comparing numbers different from comparing strings
      Comparison             Numeric   String
      Equal                    ==        eq
      Not Equal                ~=        ne
      Less Than              <, <=       lt, le
      Greater Than           >, >=       gt, ge

      35 == 35.0   ==>  true (comparing numbers)
      "35" eq "35.0" ==> false (comparing strings)
      "abc" lt "def" ==> true (comparing strings)

Boolean Values

Perl has no boolean type. It also has no keywords for "true" or "false".

Undef is always false.
Zero is false; other numbers are true.
The empty string is false; other strings are true (except the string "0" which is treated the same as the number 0).
Empty arrays and hashes are false; arrays/hashes with items in them are true.

Control Structures: If Else


Mostly the same as C.
Use elsif instead of else if
Curlies are required.
   if ($value > 35)
{
   print "Big!\n"; 
   }
   elsif ($value < 10)
   { 
   print "Small!\n"; 
   }
   else
   { 
   print "Medium!\n";
   }

Control Structures: While

Same as C.
Curlies required.
   # Prints each number from 0 to 10.
   $value = 0;
   while ($value < 10)
   {
   print $value;
   $value++;
   }

   # Prints each item in an array, REMOVING it
   # from the array in the process.
   while ($item = shift(@array))
   {
   print $item;
   }

TRY IT: While Loop

Control Structures: For

Same as in C.
   for ($i = 1; $i <= 10; $i++)
   {
   print "Counting $i\n";
   }

Control Structures: Foreach

There is also a "for each" structure for iterating through lists.
    # Iterates through each item in the array
    # WITHOUT removing it from the array.
    foreach $element (@array)
    {
    print $element;
    }

    # Iterates through each item in the hash
    # Remember that keys(%hash) returns an array.
    foreach $key (keys(%hash))
    {
    print $key;          # Prints the key
    print $hash{$key};   # Prints the item
}

TRY IT: Foreach Loop
Previous Chapter Next Chapter