The Perl Tutorial: What's Perl? (3)


Operators

Perl supports the same set of operators as most other computer languages. Operators allow a computer language to perform actions on operands. As in every computer language, Perl operators also have a certain precedence.

We've already encountered the assignment operator (=). This operator assigns a value from one variable to another:

$string1 = $string2;

The above code assigns the value of $string2 to $string1. We will now consider binary and unary arithmatic operators.

The logical operators are used mainly to control the flow of the program. Some of the logical operators that Perl supports include:

There are other operators which can also be used in Perl. We have the concatenation operator for strings (.):

$string1 . $string2

The above code will concatenate $string1 with $string2 to form a new string.

We also have the repetition operator (x), this operator will repeat a string a certain number of times specified:

$string1 x 2;

The above code will repeat $string1 twice.

The range operator allows us to use ranges, in arrays or patters:

@array = (1..50);

The above code will assign 50 elements to the array.

As we have already seen, we have a wide variety of operators that work with scalar values, but if we wanted to work with arrays we could do what is called "array splicing". Let's say we have an array with 10 values. If we want to assign values 5 and 6 to two scalar values we could do the following:

($one,$two) = @array[4,5]; #remember that arrays start at subscript 0.

In the above code we just spliced two values from the array. When we do array splicing we use the @ sign, followed by the array name, followed by brackets and the subscripts that you want separated by commas. So instead of having two lines for the above code we have one. We need to enclose the two scalar values in parentheses in order to group them

Functions