Tomislav Dyulgerov
Tomislav Dyulgerov

Reputation: 1026

Looping through characters in Perl

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;
}

Output: abcdefgh

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.

Output: h

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

Answers (4)

rubber boots
rubber boots

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

theglauber
theglauber

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

frezik
frezik

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

Eric Strom
Eric Strom

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

Related Questions