السبت، فبراير ٢١، ٢٠٠٩

Perl: You don't want to miss! -2-

This post will be about loops and conditions! Hopefully this will be too short.

Loops and if conditions are not much differnt from other langauges:
while, for, do-while, if, foreach

What seems new to me (Cx & Java developer)
- if -elseif
- until (negative of "while": while not)
- do ... until
- unless (negative of "if": if not)

What about loop controls?
- last (aka "break")
- next (aka "continue")
- redo (the amazing keyword, just redo the loop!)

while(<STDIN>) #Keep reading the standard input
{
print; #No argument? yes, it defaults to printing the magic variable: $_
if($_ > 0) {
$_--; #Decerement
redo; #Back to the top of the loop without executing the condition body!
}
}

Expression Modifier
What about rephrasing the "redo"?

redo if $_-- > 0; #Remember, the post-decrement has the lower precedence
See, the statement (action) comes before the condition in this expression modifier.

This is valid for the "if" and "unless" too. Give it a try!

هناك تعليقان (٢):

Unknown يقول...

perl is so much like shell scripting , you will find many similarities , its an easy language , can be mastered in short time , its power is apparent in 1-file operations 2-web applications , i have experienced perl myself in file operations , really awesome
P.S. take care of the special variables , they do all the work

Mohammed ElMorsy يقول...

Yeah! It leads the scripting languages for writing scripts. But I won't tend to build big applications with Perl, its OO seems immature :) ... it's built for quick scripts