Reputation: 6514
I'm fairly new to coding in Perl and am used to using C-style for loops. I'm not sure why the following program never prints a value of 4 for $l:
use strict;
use warnings;
my $minL = 4;
for (my $l = $minL; $l > 0; $l--) {
for (my $i = 0; $i + $l < $minL; $i++) {
print "$i $l\n";
}
}
Many thanks in advance.
Upvotes: 1
Views: 65
Reputation: 4371
In the first iteration:
for (my $l = $minL; $l > 0; $l--) {
$l == $minL
for (my $i = 0; $i + $l < $minL; $i++) {
So this block won't run until $l is decremented:
print "$i $l\n";
}
Change your inner loop to:
for (my $i = 0; $i + $l <= $minL; $i++) {
Upvotes: 1
Reputation: 240649
Your inner for
loop has the condition $i + $l < $minL
. If $l == $minL
, then $i + $l < $minL
will be false even if $i
is 0, so the loop runs 0 times and never prints anything.
Maybe you wanted to use <=
for the condition?
By the way, here is how you could write the same thing (assuming the <=
condition) using Perl-style foreach loops:
my $minL = 4;
for my $l (reverse 1 .. $minL) {
for my $i (0 .. $minL - $l) {
print "$i $l\n";
}
}
Upvotes: 2