Variables

Variables are interesting in Perl. You do not declare them, and you always use a $ to denote them. They come into existence at first use. For example:

   $s = "Hello\nWorld\n";
   $t = 'Hello\nWorld\n';
   print $s, "\n", $t;

Or:

   $i = 5;
   $j = $i + 5;
   print $i, "\t", $i + 1, "\t",  $j;     # \t = tab

Or:

   $a = "Hello ";
   $b = "World\n";
   $c = $a . $b;    # note use of . to concat strings
   print $c;

Since . is string concatenation, .= has the expected meaning in the same way that "+=" does in C. Therefore, you can say:

   $a = "Hello ";
   $b = "World\n";
   $a .= $b;
   print $a;

You can also create arrays:

   @a = ('cat', 'dog', 'eel');
   print @a, "\n";
   print $#a, "\n";  # The value of the highest index, zero based
   print $a[0], "\n";
   print $a[0], $a[1], $a[2], "\n";

The $# notation gets the highest index in the array, equivalent to the number of elements in the array minus 1. As in C, all arrays start indexing at zero.

You can also create hashes:

   %h = ('dog', 'bark', 'cat', 'meow', 'eel', 'zap');
   print "The dog says ", $h{'dog'};

Here, 'bark' is associated with the word 'dog', 'meow' with 'cat', and so on. A more expressive syntax for the same declaration is:

   %h = (
      dog => 'bark',
      cat => 'meow',
      eel => 'zap'
   );

The => operator quotes the left string and acts as a comma.