In this fourth part of a five-part series on scalars in Perl, you learn how to compare the value of strings; we'll also wrap up our discusssion of operators and move on to variables. This article is excerpted from chapter two of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
There are a few operators left that we are not going to go into in detail right now. Don’t worry, we will eventually come across the more important ones.
The conditional operator looks like this:a?b:c. It returnsbifais true, andcif it is false.
The range operators,..and..., make a range of values. For instance, (0..5) is shorthand notation for (0,1,2,3,4,5).
We’ve seen the comma for separating arguments to functions likeprint(). In fact, the comma is an operator that builds a list, andprint()works on a list of arguments. The operator=>works like a comma with certain additional properties.
The=~and!~operators are used to “apply” a regular expression to a string. More on these operators in Chapter 7.
As well as providing an escape sequence and backwhacking special characters,\is used to take a reference to a variable, to examine the variable itself rather than its contents. We will discuss this operator in Chapter 11.
The>>and<<operators “shift” a binary number right and left a given number of bits.
->is an operator used when working with references, covered in Chapter 11.
Table 2-1 provides the precedence for all the operators we’ve seen so far, listed in descending order of precedence.
Table 2-1.Operator Precedence
Functions that take list arguments
Infix dereference operator
! ~ \
Logical not, bitwise not, reference of
Regex match, negated regex match
* / % x
Multiplication, division, modulus, replication
+ - .
Addition, subtraction, concatenation
Left shift, right shift
< > <= >= lt gt le ge
== != <=> eq ne cmp
More comparison operators
Bitwise or, bitwise xor
Logical or, xor
Remember that if you need to get things done in a different order, you will need to use parenthesis. Also remember that you can use parenthesis even when they’re not strictly necessary, and you should certainly do so to help keep things readable. While Perl knows full well what order to do7+3*2/6-3+5/2&3in, you may find it easier on yourself to spell it out, because next week you may not remember everything you have just written.