Wednesday, October 29, 2008

Operators in PERL

I assume that examples used will explain about the usage of operators here.

1. Equality Operators :


Strings:
if ($Name eq "Ripple") { print "My Name is $Name" }
if ($Name ne "Ripple") { print "My Name is not $Name" }

Of course it would make more sense to use else here, but for the sake of examples be happy with this solution.

Numbers:
To compare numbers, use <, <=, >, >=, <> and ==.



2. If...then...else...elsif

$MyAge = 24

if ($MyAge < 18)
{ print "My age is less than 18" }
elsif ($number < 25)
{ print "My age is less than 25" }
else { print "My age is greater than 25" }

OUTPUT:
My age is less than 25

Simpler way to right If statement:

$Name = "Ripple";
print "My Name is Ripple" if $Name eq "Ripple";

Another way to use if-else:

$Size eq "Big" ? $output="BIG" : $output="small";
print $output;

if it is true, the code after the question marked will be executed. If not, the code ofter the colon will be executed. So if your if block only needs to do one statement, use "? :"



3. FOR loop...

for ($counter = 0; $counter <= 10; $counter++)
{ print $counter."," }
Output:
0,1,2,3,4,5,6,7,8,9,10,

$counter++ means, that $counter will be increased one by one and is short for $counter = $counter + 1. You can also use it with a minus, making it $counter- - . But you can do a little bit more while you are in a loop.

Place any of the commands into the loop and you con do this:

last Exit the loop immediately
redo Repeat the last run in the loop
next Proceed to the next run, don't run any command after this in the loop

The main use for those is, if you have to change the standard loop behaviour under special circumstances or rules, when you want to abort the loop and so on.

No comments: