unless ($i==3) {
print "$i is not 3";
}
is equivalent to:
if ($i==3) {}
else {
print "$i is not 3";
}
you can also have an else clause....
unless ($i==3) {
print "$i is not 3";
} else {
print "$i is 3";
}
is equivalent to:
if ($i==3) {
print "$i is 3";
}
else {
print "$i is not 3";
}
until ($i==3) {
print "$i is not 3";
$i = $i-1;
}
is equivalent to negating the condition and putting it in a while loop:
while (!($i==3)) {
print "$i is not 3";
$i = $i-1;
}
You can change the order of some expressions...for example:
if ($i==3) {
print "$i is 3";
}
is equivalent to:
print "$i is 3" if ($i==3);
other examples:
print "$i is not 3" unless $i==3;
$i=$i-1 until $i=0;
$i=$i-1 while $i>0;
$i=$i-1 foreach @myarray; #This only works using the default variable $_
{
my $a =3;
print $a;
}
print $a; #$a is gone
if ($a==1) {
print "It's one.";
} elsif ($a==2) {
print "It's two.";
} elsif ($a==3) {
print "It's three.";
} else {
print "None of these.";
}
$a++;
$a--;
$a=5;
$a=5;
++$a; #Adds one to $a
--$a; #Subtracts one from $a
print $a++; #Will print 5, then increment $a to 6
print --$a; #Will decrement $a to 4 then print 4
for (initialization; test; increment)
{
...code...
}
for ($i=1; $i<=10; $i++)
{
print $i;
} #prints 12345678910
init, test, and increment are all optional. test is a boolean value
for (;m/word/;)
{
...code...
}
You can actually use for in place of foreach....
foreach (1..10) is equivalent to for (1..10)
while ($a=<STDIN>) {
for ($i=1; $i<=10; $i++)
for ($i=1; $i<=10; $i++)
if ($a eq "THEEND") {
last;
}
else {
print "Input was $a\n";
}
}
# Last jumps here...
{
print $i;
next;
print "You'll never see this";
#next jumps here....
}
{
print $i;
redo;
} #this just prints 1 over and over
OUTER:for ($i=1; $i<=10; $i++) {
for ($x=1; $x<=10; $x++) {
if ($x==5) {
next OUTER;
}
}
}
and - &&
or - ||
if (($a<5) && ($b<5))
if (($a<5) || ($b<5))
{
...
}
{
...
}
These are short-circuit operators, meaning in the && operator, if the first expression is false, there's no need to evaluate the 2nd. In an or, if the 1st is true, there's no need to evaluate the 2nd. This is useful in something like this:
if ( ($a!=0) && ($b/$a <10) )
{
#$a being 0 would cause an error in the 2nd statement
}
Unlike in other languages, the value of the short circuit operator is
the value of the last evaluation, so you can use it for something like:
$a = $phonenum || "No phone number";
You can also use the words and and or for && and ||, but they have lower precedence, so the values of these 2 statements may be different:
$a < $b && $c < $d
$a < $b and $c < $d
Shortcut for if...then...else
if ($a==1) {
"$a is 1";
}
else {
"$a is not 1";
}
is equivalent to:
($a==1) ? "$a is 1" : "$a is not 1";