Perl basics.

Comments

Perl has only one type of comments - one line comments. Everything what starts with # and up to the end of the line is considered as comment.
print "Hello!"; # print out one word

Variables

To use variables in Perl all you need to do is to initialize them. The names of scalar variables are to start with $ sign:
$counter = 0;
$amount = 15.20;
$name = "Daniel";
print "amount = $amount\n";
As you can see from the example above we don't describe variables we just use them. You can also notice that we do not need to specify a type of a variable. Perl automatically chooses the right type based on the value assigned to a variable. Thus, one variable can store different types of data:
$a = 100;
print "\$a = $a is a number\n";
$a = 'is a text now';
print "\$a $a\n";
Scalar variables in Perl may hold the following types of values:

Please notice that Perl does not give any error message if we are trying to use an unitialized variable. For example, the following code

print "\$a = $a\n";
will print
$a =
If you want to get such messages we would suggest to use option -w for the perl interpreter and package strict in the scripts. The following code
# file: warning.pl
use strict;
print "\$a = $a\n";
if executed by
...> perl -w warning.pl
will produce the output:
Name "main::a" used only once: possible typo at comments.pl line 3.
Use of uninitialized value in concatenation (.) or string at comments.pl line 3.
$a =
To correct this error we need to declare the variable $a by using the my function:
# file: nowarning.pl
use strict;
my $a = 12;
print "\$a = $a\n";

Strings

String literals can be created with either single quotes or double quotes. To illustrate difference between them let's consider the following code:
use strict;
my $name = "Bob";
print "Hello, $name\n";
print 'Hello, $name\n';
This code generates the output:
Hello, Bob
Hello, $name\n
As you can see double quotes strings substitute variable names with their values and also treat backslashes as an escape character, which allows to print special characters like new line character (\n) or a dollar sign (\$). Single quoted strings don't do that.

Array variables

Arrays in Perl are ordered collection of scalars. Perl allows these scalars to have different types. Array names begin with the @ character:
# an array of data
my @collection = ("My name", 123, 'string', 3.97);
Perl also allows us to print all elements of the array at once. The following example shows how to do that, please also pay attention to the difference between double and single quotes and also array printed outside of any quotes:
use strict;
my @collection = ("My name", 123, 'string', 3.97);
print "Within double quotes: @collection\n";
print "Outside any quotes: ", @collection, "\n";
print 'Within single quotes: @collection', "\n";
Within double quotes: My name 123 string 3.97
Outside any quotes: My name123string3.97
Within single quotes: @collection

As in C++, Perl arrays start at element 0. For @collection, the elements are:

  • 0: "My name"
  • 1: 123
  • 2: 'string'
  • 3: 3.97
    To access an individual element in an array use
    $array_name[index]
    For example, to print the second element of the @collection use:
    print "Second element: $collection[1]\n";
    

    A very useful array related variable is $#array_name. This variable stores the last index of the array. For example, for the array described above the following line of code

    print "last index: $#collection\n";
    
    generates:
    last index: 3
    There is a very useful predefined array in Perl @ARGV that contains all the arguments of the script used in the command line. The following code prints out the first three of these arguments:
    print "  Argument one: $ARGV[0]\n";
    print "  Argument two: $ARGV[1]\n";
    print "Argument three: $ARGV[2]\n";
    
    Of course, variable $#ARGV contains the number such argument minus one.

    Please read about the following functions for arrays:

    Associative arrays

    Associative arrays (called hashes in Perl) are arrays that are indexed by strings instead of numbers. A hash variable (an associative array) is defined as a to be a collection of key/value pairs. The keys must be unique strings; the values can be any scalars. A hash variable name begins with the percent sign. We need to use operator => to define each pair in the array:
    my %student = (
      name  => "Bob",
      age   => 21,
      phone => "123-4567",
      gpa   => 3.79
    );
    
    Accessing a value in has is similar to accessing values in usual arrays, indexed with the key in curly braces, instead of a number within square brackets:
    $student{gpa} = 3.8;
    
    The key does not need to be quoted within the curly braces (unless the key contains a whitespace character).

    The most commons way to process a hash is by looping through the keys. Built-in function keys() takes a hash variable as an argument and returns an array containing all the keys of the variable. The following example prints all keys of a hash variable in alphabetical order:

    # file: hash_keys.pl
    use strict;
    my %customer = (
      name   => "Bob",
      phone  => "123-4567",
      street => "Hal Greer Blvd, #1",
      city   => "Huntington",
      state  => "WV",
      zip    => 25755
    );
    my @k = keys(%customer);
    my @sk = sort(@k);
    print "The keys are: @sk\n";
    

    Operators

    Arithmetic
    Operator Description Example
    + addition $a + $b
    - subtraction $a - 12
    * mutliplication $a * $b
    / division $a / 3
    % modulus 15 % $a
    ** exponention $a ** 3 (a cubed)
    ++ increment ++$a or $a++
    -- decrement --$a or $a--
    String
    . string concatenation $str = "Hi " . "Bob" # now $str="Hi Bob"
    x string replication $a="test ";
    $b = $a x 3; # now a = "test test test"
    Numerical Comparison
    < less than $bad = $gpa < 1.5;
    <= less than or equal $good = 3.5 <= $gpa;
    > greater than $very_good = $gpa > 3.9;
    >= greater than or equal $not_bad = $gpa >= 2.3;
    == equals to $perfect = $gpa == 4;
    != not equal to $not_perfect = $gpa != 4;
    <=> compare. The result of this operator is equal to either 1, 0, or -1. It's equal to 1 if the first operand is greater than the second, zero if they are equal, and -1 if the second is greater than the first. $comparison = $a <==> 123;
    String Comparison
    lt less than $before = $name lt "b";
    le less than or equal $a_name = $name le "a";
    gt greater than $after = $name gt "Tester";
    ge greater than or equal $after_P = $name ge "O";
    eq equivalent to $is_Bob = $name eq "Bob";
    ne not equal to $not_Bob = $name ne "Bob";
    cmp The string comparison operator evaluates to either 1, 0, or -1. $comparison = $name cmp "Bob";
    Logical
    &&
    and
    logical and $may_drive = ($age>16) && $has_a_license;
    ||
    or
    logical or $can_retire = ($age>65) or $rich;
    |
    not
    logical not $keep_working = ! $done;