Quantcast
Viewing latest article 3
Browse Latest Browse All 8

Perl Operators

Perl Operators

What Number Please?

Without operators, there is no point to scripting. Assigning values to variables and stuff would serve no purpose, unless you just wanted to rename the number one $that_number_that_I_can_never_remember – and we all have to admit that’s a little bit stupid, right?

There are three different types of operators:assignment, comparison, and mathematical. Assignment operators give a value to a variable, comparison operators compare two values and give a third value based on what they find, and mathematical operators do the math so you don’t have to. And here they are:

Assignment Operators

= Makes the value of the variable on the left side equal to whatever is on the right.
+= Adds the value of the right side to the left side and makes the variable on the left equal to it.
-= Same as above, only subtracts instead of adds.

Comparison Operators

< Returns a true value if the value on the left is less than that on the right. Otherwise false.
> Same as above, but the other way around.
>= Returns a true value if the value on the left is greater than or equal to that on the right. False if not.
<= Are we seeing a pattern here?
== Returns a true value if the values on both sides are equal; otherwise returns a false.
eq The same as above, but rather than comparing values, it compares strings of text.
!= Returns a true value if the value on the right is not equal to that on the left. False if they are equal.
ne Again, same as above, but for strings of text.

Comparison Operators are perfect for those if/else statements I talked about. They work something like this:

#I assign the value of 5 to $stuff.

$stuff = 5;

# Then I compare it and react to its value.

if ($stuff < 5) {

print “Runt!”;

} elsif ($stuff >= 6) {

print “Too big, man!”;

} else {

print “I guess that’ll do.”;

}

Mathematical Operators

* Multiplies the two values together.
/ Divides two values.
+ Adds two values.
- Subtracts two values.
++ Adds 1 to the value on the left (so if $i were equal to 1, $i++ would equal 2).
Subtracts 1 from the value on the left.

You get the idea. Of course, with the exception of the last two operators, mathematical operators aren’t any good unless you use an assignment operator for storing the value. For these to be of any use, you’d have to do something like this:

 $stuff = 5 * 3;




Viewing latest article 3
Browse Latest Browse All 8

Trending Articles