Title here
Summary here
Here we use range
to sum the numbers in a slice. Arrays work like this too.
my @nums = (2, 3, 4);
my $sum = 0;
foreach my $num (@nums) {
$sum += $num;
}
print "sum: $sum\n";
range
on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the blank identifier _
. Sometimes we actually want the indexes though.
for (my $i = 0; $i < scalar @nums; $i++) {
my $num = $nums[$i];
if ($num == 3) {
print "index: $i\n";
}
}
range
on hash iterates over key/value pairs.
my %kvs = ("a" => "apple", "b" => "banana");
while (my ($k, $v) = each %kvs) {
printf "%s -> %s\n", $k, $v;
}
range
can also iterate over just the keys of a hash.
foreach my $k (keys %kvs) {
print "key: $k\n";
}
range
on strings iterates over characters. The first value is the starting byte index of the character and the second the character itself.
use utf8;
my $str = "go";
for (my $i = 0; $i < length($str); $i++) {
my $c = substr($str, $i, 1);
print "$i $c\n";
}
To run the Perl script, save the code in a file with .pl
extension and then execute it using the Perl command.
$ perl your_script.pl
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 g
1 o