note
kennethk
The [doc://perlop#Auto-increment-and-Auto-decrement|++] is after variable, so it increments after you test it; however, the print is a separate statement. If you used [doc://perlsyn#Compound-Statements] instead of [doc://perlsyn#Statement-Modifiers], your code would better reflect the actual flow and would look like:
<c>$i=0;
if ($i++) {
print 'first=' , $i, ', ';
}
if ($i++) {
print 'middle=' , $i, ', ';
}
if ($i++) {
print 'last=' , $i, ', ';
}
if ($i++) {
print 'beyond=' , $i, ', ';
}
</c>
For what you want, you probably mean:
<c>$i=0;
if ($i++) {
print 'first=' , $i - 1, ', ';
}
if ($i++) {
print 'middle=' , $i - 1, ', ';
}
if ($i++) {
print 'last=' , $i - 1, ', ';
}
if ($i++) {
print 'beyond=' , $i - 1, ', ';
}
</c>
which is admittedly a little awkward. More natural would be to post-increment after your [doc://print], except you clearly intend the incrementation to happen independently of whether the print happens. Perhaps
<c>
$i=0;
print 'first=' , $i, ', ' if $i;
$i++;
print 'middle=', $i, ', ' if $i;
$i++;
print 'last=' , $i, ', ' if $i;
$i++;
print 'beyond=', $i if $i;
$i++;
</c>
or
<c>
my $i=0;
outputter('first', $i++);
outputter('middle', $i++);
outputter('last', $i++);
outputter('beyond', $i++);
sub outputter {
my ($txt, $i) = @_;
print "$txt=$i, " if $i;
}
</c>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-712372">
<hr />
<p>#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.</p>
</div></div>
1058791
1058791