Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calculating on hashes? 1

Status
Not open for further replies.

klkot

Programmer
Joined
Jun 6, 2007
Messages
18
Location
US
I'm very new to Perl and trying to get things to work. I'm working with a dataset that originally looks like this:
ID Intdaymiss Daysobs
2611 . 12
2611 5 28
2612 . 0
2613 0 .
2613 5. 5
2613 17 50

I want to print output to an outfile that looks like this:
ID TotalDM TotalDO 1-DM/DO (ADhash)
2611 5 30 solution
2612 . 0 solution
2613 53 22 solution

The following section worked where I created a hash for DM and a hash for DO to sum the DM and DO per patientid (key).

%dmhash = {};
%dohash = {};

for ($i=1; $i<@id; $i++){
$dmhash{$id[$i]} += $intdaymiss[$i];
$dohash{$id[$i]} += $daysobs[$i];}
foreach my $key (sort keys %dmhash) {
print "$key = $dmhash{$key}\n";}



Now I'm trying to references the hashes to make calculation of a new ADhash (which is the column I'm making the calculation for) but something is wrong with the way I'm referencing the hashes for calculation. Do you know how to fix it and how to print the solution in the form I want?

%adhash = {};
while(@patientid){
if(($dohash{$patientid})=0) {
$adhash{$patientid}=nil;
}
else{$adhash{$patientid} = 1-(($dmhash{$patientid})/($dohash{$patientid}));
}
}

Thanks!
 
Look at this line

Code:
if(($dohash{$patientid})=0) {

You're doing an assignment instead of an equality test. Use == instead.

- Miller
 
Thanks Miller. I used the == but it still was not able to print the adhash. Does anyone know the code to make the output print in the form I want it to?

I really appreciate it any advice ;)
 
Maybe this will help steer you in the right direction:

Code:
use Data::Dumper;
my %results = ();
readline <DATA>; #skip header
while (<DATA>) {
   chomp;
   my ($id, $dm, $do) = split(/\s+/);
   $results{$id}{TotalDM} += ($dm =~ /^(\d*)\.?$/) ? $1 : 0;
   $results{$id}{TotalDO} += ($do =~ /^(\d*)\.?$/) ? $1 : 0;
}
print Dumper \%results;
__DATA__
ID       Intdaymiss      Daysobs
2611     .                 12
2611     5                 28
2612     .                  0
2613     0                  .
2613     5.                 5
2613     17                50

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top