You could go faster by completing your rangeHash straightaway without going through dataHash first.

Assuming your ranges can't overlap, all you have to do is compute the range from the value and use it as a key. For example: (the getRange sub is far from being perfect, I went for a simple solution since you probably already have code to check which range you are in) :

use Data::Dumper; sub getRange { my $value = shift; warn "Unexpected value $value," and return if $value < 1; return '1-19' if $value < 20; return '20-29' if $value < 30; return '30-39' if $value < 40; return '40-59' if $value < 60; warn "Out of range value $value," and return; } my %hits; while (<DATA>) { my $range = getRange($_); $hits{$range}++ if defined $range; } print Dumper \%hits; __DATA__ 12 14 15 20 21 50 42
The result is :
$VAR1 = { '1-19' => 3, '40-59' => 2, '20-29' => 2 };


In reply to Re: Perl hit counter for multiple ranges, optimization or options in other languages? by Eily
in thread Perl hit counter for multiple ranges, optimization or options in other languages? by SaktiMonk

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.