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

Why with the C for loop again? There are, in my opinion, two better options: a while loop, or a Perl for loop. Consider:

while ($count--) {

or

for (1 .. $count) {

I'd go for the for loop variant as it makes it clear we are iterating $count times and $count isn't used in the loop body so it doesn't need to be decremented.

True laziness is hard work

Replies are listed 'Best First'.
Re^3: why i cant print reading hash table?
by Athanasius (Archbishop) on Nov 20, 2013 at 06:21 UTC

    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,

      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