in reply to Re^2: why i cant print reading hash table?
in thread why i cant print reading hash table?

Hello GrandFather,

In my reply I was actually addressing this warning generated by the OP:

Useless use of private variable in void context at...

(I should have made this explicit.) I certainly agree that either a while or a foreach loop would be preferable here. Unfortunately, neither of your suggested alternatives results in the same number of iterations as the original:

16:05 >perl -wE "my $c = 0; for (my $n = 3; $n >= 0; $n--) { ++$c; } s +ay $c;" 4 16:05 >perl -wE "my $c = 0; my $n = 3; while ($n--) { ++$c; } say $c;" 3 16:05 >perl -wE "my $c = 0; my $n = 3; for (1 .. $n) { ++$c; } say $c; +" 3 16:05 >

And since the loop is likely incomplete (see my comments regarding $outfile), we cannot be sure that $count won’t be used for something later on in the loop — in which case, the foreach version of the loop would provide the values in their reverse order. So the safest alternative is probably:

while ($count-- >= 0) {

Update 1: Except that the value of $count within this loop is always one less than its “proper” value.

Update 2: Upon reflection, I now realise that GrandFather’s alternative loops were not intended as equivalents to the original, but as corrections to it, since it’s most likely that the OP code meant to loop for exactly $count iterations. If so, I apologise to GrandFather for the misreading.

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^4: why i cant print reading hash table?
by GrandFather (Saint) on Nov 20, 2013 at 07:09 UTC

    Nice that you++ picked up the off by one which exactly illustrates the problem with C for loops. I don't much like the while loop solutions because they don't make the number of iterations clear, particularly in conjunction with the post decrement operator - that's just far too subtle.

    Actually, to get the count right and clear I'd:

    for (1 .. $count + 1) {

    If the values are required I'd:

    for my $value (reverse 0 .. $count) {

    which makes it very clear that the values are required in reverse order and the span of values required, but obfuscates the number of iterations somewhat.

    True laziness is hard work