garbage777 has asked for the wisdom of the Perl Monks concerning the following question:
I have to print a random hash value and the associated key if it satisfies certain conditions shown below. Below is the code I wrote.k1 0.2 k2 0.9 k3 1 k4 1.2 k5 1.3 k6 2 k7 2.2 k8 2.7 k9 2.76 k10 3.001 k11 3.12 k12 3.2 k14 3.22 k15 3.3 k16 3.34 k17 3.4 k18 3.62 k19 3.8 k20 3.89
If I try to sample large files with this code, it looks like it is very slow. Therefore allow me to ask if there is any better way to write this code. Any help from fellow monks is appreciated. best,#!/usr/bin/perl use strict; use warnings; my %netHash; my $capval; my ($capVal_1_Hash, $capVal_2_Hash, $capVal_1_Hash, ....., $capVal_9 +9_Hash, $capVal_1_Hash) ; open(IFH, "<", "./chance.txt"); while(<IFH>) { chomp; my($nx,$ny) = split; $netHash{$nx} = $ny if ($ny > 1); } foreach $val (keys %netHash) { if($netHash{$val} > 1.0) { if($netHash{$val} < 1.4) { my ($x1, $y1) = ($val,$netHash{$val}); $capVal_1_Hash{$x1} = $y1 if defined $y1; } } if($netHash{$val} > 1.4) { if($netHash{$val} < 1.9) { my ($x2, $y2) = ($val,$netHash{$val}); $capVal_2_Hash{$x2} = $y2 if defined $y2; } } ... ... if($netHash{$val} > 99.2) { if($netHash{$val} <99.8) { my ($x99, $y99) = ($val,$netHash{$val}); $capVal_99_Hash{$x99} = $y99 if defined $y99; } } if($netHash{$val} > 100.1) { if($netHash{$val} < 100.9) { my ($x100, $y100) = ($val,$netHash{$val}); $capVal_100_Hash{$x100} = $y100 if defined $y100; } } } printHash(\%capVal_1_Hash); printHash(\%capVal_2_Hash); ... ... printHash(\%capVal_99_Hash); printHash(\%capVal_100_Hash); close IFH; } sub printHash { my $href = shift; my $RandKey = (keys %{$href}) [int(rand(scalar (keys %{$href})))]; print "$RandKey $href->{$RandKey}\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: better way to printing random hash key and its value
by merlyn (Sage) on Dec 23, 2006 at 04:54 UTC | |
|
Re: better way to printing random hash key and its value
by GrandFather (Saint) on Dec 23, 2006 at 06:02 UTC | |
|
Re: better way to printing random hash key and its value
by kyle (Abbot) on Dec 23, 2006 at 05:28 UTC | |
by kyle (Abbot) on Dec 23, 2006 at 05:51 UTC | |
|
Re: better way to printing random hash key and its value
by Util (Priest) on Dec 23, 2006 at 06:28 UTC |