On Apr 12, 8:35 pm, msan...@gmail.com (Magne Sandøy) wrote:
> Hi.
>
> I'm new to perl, and I stumbled across a strange behavior in my for loop.
> In the following code, the second for loop actually counts way passed
> what I expected, and actually stops at "yz" and not "z" as expected.
> As shown by the third for loop, incrementing the letters, seems to give
> me the desired output in each loop.
> What is going on here?
>
> #!/usr/bin/perl
> use warnings;
> use strict;
>
> my $letter = "u";
>
> for ("u".."z"){
>     print " $_ ";
>
> }
>
> print "\n\n";
>
> for ($_="u"; $_ le "z"; $_++){
>     print " $_ ";
>
> }
>
> print "\n\n";
>
> for(1..7){
>     print " $letter ";
>     $letter++;
>
> }

This is the trickiness of magical autoincrement. See: perldoc perlop.

Once, you increment $_ = 'z' in your loop:

    perl -le "$_='z';$_++; print"     ---> prints 'aa';

And, the incrementing continues until, finally, you reach  'yz':

   perl -le "$_='yz';$_++; print $_"  ---> prints 'za'

Why did it stop at 'yz'... you ask... Because the string 'za'
would generate a value 'longer than z' itself .

Similiarly, if your range had been 'uu'..'zz', the increment
would have stopped at 'zyz' because incrementing would
then produce 'zza'.

Clear as mud?  Did you say 'Hell, no'...?  Go then and
meditate on  autoincrement magic,  grasshopper. When
enlightenment comes, please report back and  explain it
to us too...

--
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to