The biggest time sink I see is that you look up $netHash{$val} 100 times in each loop.

Untested code, via top-of-my-head refactoring:

#!/usr/bin/perl use strict; use warnings; # Do you really need named hashes for later code? my @capVal_hashes = ( undef, \( my %capVal_1_Hash ), \( my %capVal_2_Hash ), \( my %capVal_3_Hash ), ... \( my %capVal_99_Hash ), \( my %capVal_100_Hash ), ); open IFH, '<', './chance.txt' or die; my %netHash; while (<IFH>) { my ( $key, $val ) = split; next if not $val > 1; my $hash_num = ( $val <= 1.0 ) ? undef : ( $val < 1.4 ) ? 1 : ( $val == 1.4 ) ? undef # Intentional gaps? : ( $val < 1.9 ) ? 2 : ( $val == 1.9 ) ? undef # Intentional gaps? ... ... : ( $val < 99.2 ) ? 98 # XXX Assumed : ( $val == 99.2 ) ? undef # Intentional gaps? : ( $val < 99.8 ) ? 99 : ( $val <= 100.1 ) ? undef # Intentional gaps? : ( $val < 100.9 ) ? 100 : undef ; if ( defined $hash_num ) { $capVal_hashes[$hash_num]{$key} = $val; } } close IFH or warn; foreach my $href ( @capVal_hashes ) { next if not defined $href; my @keys = keys %{ $href }; my $random_key = @keys[ rand @keys ]; my $random_val = $href->{$random_key}; print "$random_key $random_val\n"; }


In reply to Re: better way to printing random hash key and its value by Util
in thread better way to printing random hash key and its value by garbage777

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.