| |||||||||
|
| |||||||||
Perl Primer - Chapter 3 -by Linda Naughton
OperatorsStandard C-style operators (including ++, +=, &&, etc.)Comparing numbers different from comparing strings
Comparison Numeric String
Equal == eq
Not Equal ~= ne
Less Than <, <= lt, le
Greater Than >, >= gt, ge
35 == 35.0 ==> true (comparing numbers)
"35" eq "35.0" ==> false (comparing strings)
"abc" lt "def" ==> true (comparing strings)
Boolean ValuesPerl has no boolean type. It also has no keywords for "true" or "false".Undef is always false. Zero is false; other numbers are true. The empty string is false; other strings are true (except the string "0" which is treated the same as the number 0). Empty arrays and hashes are false; arrays/hashes with items in them are true. Control Structures: If ElseMostly the same as C. Use elsif instead of else if Curlies are required.
if ($value > 35)
{
print "Big!\n";
}
elsif ($value < 10)
{
print "Small!\n";
}
else
{
print "Medium!\n";
}
Control Structures: WhileSame as C.Curlies required.
# Prints each number from 0 to 10.
$value = 0;
while ($value < 10)
{
print $value;
$value++;
}
# Prints each item in an array, REMOVING it
# from the array in the process.
while ($item = shift(@array))
{
print $item;
}
TRY IT: While Loop Control Structures: ForSame as in C.
for ($i = 1; $i <= 10; $i++)
{
print "Counting $i\n";
}
Control Structures: ForeachThere is also a "for each" structure for iterating through lists.
# Iterates through each item in the array
# WITHOUT removing it from the array.
foreach $element (@array)
{
print $element;
}
# Iterates through each item in the hash
# Remember that keys(%hash) returns an array.
foreach $key (keys(%hash))
{
print $key; # Prints the key
print $hash{$key}; # Prints the item
}
TRY IT: Foreach Loop
|
![]()
| ||||||||