Conditionals and Loops:
if($var == 1) {
print "1\n";
}
elsif($var == 2) {
print "2\n";
}
else {
print "?\n";
}
unless($no) {
print "No is true";
}
Another syntax of the IF statement:
print "Hello" if(condition);
for and foreach loops are the same in Perl
for(my $i=0; $i<10; i++) {
...
}
for(@array) {print;}
for $i (@array) {print $i;}
while(<>) {print;}
until($i>2) {...}
do "myfile.pl";
Modifying statments with IF, UNLESS, UNTIL, and WHILE
while(<>) {
print "Too big!\n" if $_ > 100;
}
die "Cannot open file.\n" unless open($filename);
print while(<>);
do {
# this is an implemented do...while statement
# it is not a TRUE loop and cannot use control statements
print;
} while(<>);
NEXT, LAST, and REDO statments:
Next goes to the label again, last makes it the final, and redo does the
statment again without evaluating the loop's condition.
NUMBER: while(<>) {
next NUMBER if /^-/;
print;
}
COMMENTS: while(<>) {
# Strips comments (using last statement)
last COMMENTS if !/^#/;
}
do {
print;
} while(<>);
Creating a SWITCH statment with labels, since there is no built in switch
statement in Perl:
while(<>) {
SWITCH: {
/run/ && do {
$mess = "Running";
last SWITCH;
};
/stop/ && do {
$mess = "Stopped";
last SWITCH;
};
DEFAULT: {
$mess = "No match";
}
}
}
INPUT: $line = <>;
if($line !~ /exit/) {
print "Try again";
goto INPUT
}