Reputation: 1026
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
Upvotes: 6
Views: 4427
Reputation: 15204
In perl, the (++) increment operator is magical, whereas the decrement operator is not ...
as alternative to Eric's modification, you could simply do:
for (my $file = 'h'; $file ge 'a'; $file=chr((ord$file)-1)) {
print $file;
}
for counting the characters down.
Upvotes: 3
Reputation: 29625
Yes, the magic behavior is only for auto-increment:
http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement --> "The auto-increment operator has a little extra builtin magic to it."
Upvotes: 1
Reputation: 2316
The '++' operator is magical to work on strings in interesting ways. The Camel, 3rd edition, page 91, gives these examples:
print ++($foo = '99'); # prints '100'
print ++($foo = 'a0'); # prints 'b1'
print ++($foo = 'Az'); # prints 'Ba'
print ++($foo = 'zz'); # prints 'aaa'
The '--' operator does not have this magic.
Upvotes: 2
Reputation: 40152
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;
}
Upvotes: 14