On 1/13/07 16:04, in article
rm4o74-, "Mark
Hobley" <> wrote:
> The following loop works fine in Perl:
>
> for ($l = 'a'; $l le 'y'; $l++) {
> print "$l";
> }
>
> However, if I try to loop from a through to z, the loop does not work:
>
> for ($l = 'a'; $l le 'z'; $l++) {
> print "$l";
> }
>
> I know that a for each loop would work, but that is not what I want.
>
I think you're expecting: abcdefghijklmnopqrstuvwxyz
And if that's what you want, you must use ne instead of le to end the loop.
for ($l = 'a'; $l ne 'z'; $l++) {
print "$l";
}
If you replace
print "$l";
with
print "$l ";
you can see what's happening. Change the comparison from le the ne, and the
loop stops at z, but with le, the loop does not stop until zz is less than
z.
Try this little experiment.
print join(' ', sort qw( a b c x y z aa bb cc xx yy zz )), "\n";
There are two things happening in your second loop. First, Auto-increment
for string data is smarter than you expect, maybe too smart. The next value
after z is aa. Second, operators like lt, le, eq, ne, ge, and gt are
stringwise comparisons. This means the result of a comparison reflects the
sorting order of the strings, and as you see from the experiment, aa is less
than z.
--
Regards,
Mark