Character Intersection in Perl

I have a rather difficult task: figuring out some strange behavior when going through characters in Perl using a for loop. This piece of code works as expected:

 for (my $file = 'a'; $file le 'h'; $file++) { print $file; } 

Output: abcdefgh

But when I try the loop through the characters back, 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 does not behave the way I think it happens when using characters?

Does anyone have any ideas on this? I am very grateful for your help!

Hi,

Tommy

+6
source share
4 answers

The auto decrement operator is not magic, according to perlop

You can do something like this:

 for my $file (reverse 'a' .. 'h') { print $file; } 
+14
source

In perl, the increment operator (++) is magic, while the decrement operator is not ......

as an alternative to modifying Eric, you can simply do:

 for (my $file = 'h'; $file ge 'a'; $file=chr((ord$file)-1)) { print $file; } 

to count the characters down.

+3
source

The operator "++" magically works on chains in interesting ways. Camel, 3rd edition, p. 91, gives the following 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.

+2
source

Yes, magic behavior only for auto zoom:

http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement → "The automatic increment statement has a little extra built-in magic for it."

+1
source

Source: https://habr.com/ru/post/907350/


All Articles