Hi Magne,

On Tuesday 13 Apr 2010 10:37:15 Magne Sandøy wrote:
> Shlomi Fish wrote:
> > Hi Magne,
> > 
> > On Tuesday 13 Apr 2010 06:35:51 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 " $_ ";
> >> 
> >> }
> > 
> > "le" is the string equivalent of "<=" (less than or equal). You probably
> > want "lt" instead here. A program using it yields the following:
> > 
> > {{
> > 
> >  u  v  w  x  y  z
> >  
> >  u  v  w  x  y
> >  
> >  u  v  w  x  y  z  aa
> > 
> > }}
> > 
> > Regards,
> > 
> >     Shlomi Fish
> >     
> >> print "\n\n";
> >> 
> >> for(1..7){
> >> 
> >>     print " $letter ";
> >>     $letter++;
> >> 
> >> }
> 
> Hi.
> 
> So, what happened to the e in le, less than or "equal" to. In my
> opinion, "z" == "yz", would be incorrect, even tough that is what
> trigers the exit loop response. Try using "eq", and hopefully you
> understand my frustration.

"eq" will exit immediately:

{{{
shlomi:~$ cat t2.pl
#!/usr/bin/perl

use warnings;
use strict;

for ($_="u"; $_ eq "z"; $_++){
    print " $_ ";
}
print "\n";
shlomi:~$ perl t2.pl

shlomi:~$ 
}}}

The C-style for-loop continues as long as the condition is true and stops once 
it is false. "le" evaluates to true for all the strings in "u".."z" and beyond 
("aa", etc.) and so the loop doesn't terminate there.

Regards,

        Shlomi Fish

> There has to be something I have misunderstood.
> 
> Brgds
> Magne.

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Parody on "The Fountainhead" - http://shlom.in/towtf

Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

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