in reply to Calculating/adding byte counts of array elements

TIMTOWTDI (and not quite redundant):

This alternate also works:

#!/usr/bin/perl use 5.016; use warnings; # 1048190 my @arr = ("Hello, my name is John", "How are you?", "blah (blah)", "", "blivitz is in the last line.", ); my $count = 0; for my $line(@arr) { say $count . " " . $line; $count += length($line); }

Producing:

C:\>1048190.pl 0 Hello, my name is John 22 How are you? 34 blah (blah) 45 45 blivitz is in the last line.

Use of printf or sprintf is left as an exercise for the OP... altho the initialization of $counting = '00000000'; should be satisfactory too.

If I've misconstrued your question or the logic needed to answer it, I offer my apologies to all those electrons which were inconvenienced by the creation of this post.

Replies are listed 'Best First'.
Re^2: Calculating/adding byte counts of array elements
by AnomalousMonk (Archbishop) on Aug 07, 2013 at 07:04 UTC
    ... initialization of  $counting = '00000000'; should be satisfactory ...

    Initializing  $count as a numeric string with a bunch of leading zeros will see the leading zeros vanish after the first numeric operation 'numifies' the scalar — even if it's an operation with zero!.

    >perl -wMstrict -le "my $count = '00000000'; print qq{'$count'}; ;; $count += 42; print qq{'$count'}; " '00000000' '42'

      Initializing $count as a numeric string with a bunch of leading zeros will see the leading zeros vanish after the first numeric operation 'numifies' the scalar — even if it's an operation with zero!

      So do not numify it but use Perl's little quirks to do the trick:

      perl -wMstrict -le 'my $count = "00000000"; print qq{"$count"}; ++$count for 1 .. 42; print qq{"$count"};'

      Cheers, Sören

      Créateur des bugs mobiles - let loose once, run everywhere.
      (hooked on the Perl Programming language)