in reply to sprintf and for loop weirds???

Your for loop should read ...

for (my $n = 0; $n <= scalar(@a); $n++) { ... }

Note the change in operator - Your code was only doing one iteration through the loop while $n was less than 1 and not less than or equal to 1. As such, it was only iterating through the loop once and setting $b[0] and not $b[1] - If you had more values in @a, you would have found it iterating through and acting on all except the last value.

 

Ooohhh, Rob no beer function well without!

Replies are listed 'Best First'.
Re: Re: sprintf and for loop weirds???
by blakem (Monsignor) on Nov 04, 2001 at 16:15 UTC
    Of course it "should" have read:
    for my $n (0..$#a) { ... }
    to avoid the possiblity of the off-by-one mistake in the first place. ;-)

    Update: or for (@a) as larsen notes below....

    -Blake

      Or even more robustly with ...

      for my $n ($[..$#a) { ... }

      For the rare possibility where the first index of arrays may be non-zero as a result of some other strange code obfuscation. :-)

      Update : push(@b, sprintf("%.2f", $_)) foreach @a; as suggested by larsen may be nicer and much prettier, but hey! I like obfuscated code :-)

       

      Ooohhh, Rob no beer function well without!

        Looks like the perfect place for map.
        my @b = map {sprintf("%.2f",$_)} @a;

        Oh, you said obfuscated.... hows this for a first step down obfuscated lane:

        my @b = split' ',sprintf" %.2f"x@a,@a;
        one more step, and I'm done:
        s;;sprintf" %.2f"x@a,@a;e;my@b=split;

        -Blake

Re: Re: sprintf and for loop weirds???
by chipmunk (Parson) on Nov 04, 2001 at 21:01 UTC
    scalar(@a) returns the number of elements in @a, not the index of the last element. Using $n <= scalar(@a) will iterate an extra time, past the end of the array. The original poster's use of $n < scalar(@a) was correct.

    In fact, after fixing the missing parentheses in both snippets, both snippets produce the expected results. However, the missing parentheses make it clear we're not looking at the original poster's actual code.