I'm having quite a difficulty, figuring out some strange behavior when looping through symbols in Perl, using the for
loop.
This code snippet works just as expected:
for (my $file = 'a'; $file le 'h'; $file++) {
print $file;
}
But when I try the loop through the symbols backward, like this:
for (my $file = 'h'; $file ge 'a'; $file--) {
print $file;
}
gives me the following as a result.
Maybe the decrement operator doesn't behave as I think it does when symbols are involved?
Does anybody have any ideas on the matter? I'd really appreciate your help!
Regards,
Tommy
The foreach keyword is probably the easiest and most often used looping construct in Perl. Use it for looping through the items in an array. Here we're creating an array and initializing it with three strings, then displaying the strings by looping through the array with foreach and printing the strings with print.
You can access the first characters of a string with substr(). To get the first character, for example, start at position 0 and grab the string of length 1.
length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.
The auto-decrement operator is not magical, as per perlop
You can do something like this though:
for my $file (reverse 'a' .. 'h') {
print $file;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With