Are you asking how to get a total of all the results printed by printf "found %d zeros\n", $included_length =~ tr[0][];?

Update: I'll go with that assumption, and that you're looking for an elegant solution, by some subjective definition of elegant. A word of warning; elegance may be in the eye of the beholder. Anyway, here's my stab at it:

use strict; use warnings; no warnings 'once'; use feature 'say'; use List::Util 'reduce'; my $cgs = '10001011101010010101101000010101101011101111010100101010101 +0'; sub substr_at { substr $_[0], $_[1], $_[2]-$_[1]; } sub count_zeros { ( my $string, local $_ ) = @_; substr_at( $string, ( split )[1,2,1] ) =~ tr[0][]; } say reduce { $a += count_zeros($cgs,$b) } 0, <DATA>; __DATA__ junk 5 15 junk 23 59 junk 18 34 junk 10 20 junk 9 19 junk 40 49

Here's how it works:

And the reason I think it's elegant is that it is uncluttered, and seems to flow nicely. At any level, from the low end (substr_at) to the high end (reduce), you can look at what's happening and understand without spending too much time trying to grok the code.

Keep in mind though, any time you're summing anything, there's a loop involved, whether you see it or not. In the code I provided, "reduce" loops over the contents of <DATA>. Internally there are other loops as well, such as the one that the transliteration operator must use to count matches in a string. But even though we know the loops are there, it's nice to work at a level of abstraction where we're not boringly typing out "foreach..."


Dave


In reply to Re: Summing Variables in foreach loop by davido
in thread Summing Variables in foreach loop by ccelt09

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.