Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Push Function and Hash

by eepvesity (Initiate)
on Mar 28, 2013 at 00:07 UTC ( #1025827=perlquestion: print w/ replies, xml ) Need Help??
eepvesity has asked for the wisdom of the Perl Monks concerning the following question:

I am a bit stumped.

I have two files. Each file has several columns delimited by single space. There is a leading whitespace. I am only interested in columns 1 and 2. Column 1 is made up of names while column 2 is cholesterol level.

Some names are in both files, so I only want to focus on those names in both.

Knowing this, I have decided that a hash of arrays is an appropriate data structure, so my data is organized as:

Patient Cholesterol level John Kay 151 128 Sally Gi 174 145

There are other patients.

Using the split function, I can designate columns 1 and 2 as various variables, so column 1 = $patient (key) and column two = $level (value) for %health.

I can push $level into an array like so: push (@{($health{$patient}}, $level); However, what if I want to do something with each cholesterol list for each patient? For example, if I wanted to list the levels from lowest to highest, would I use a loop in which I can write:  @levelssorted = sort {$a <=> $b} @{($health{$patient}); and the level numbers for each patient would then be from lowest to highest?

Any help is welcome. Thank you.

Comment on Push Function and Hash
Select or Download Code
Re: Push Function and Hash
by tangent (Deacon) on Mar 28, 2013 at 01:32 UTC
    Once you have your files read in using  push(@{$health{$patient}},$level); you should end up with a structure like so:
    %health = ( 'John Kay' => [151,128], 'Sally Gi' => [174,145], );
    You can then iterate through the hash of arrays using while or for:
    while ( my ($patient,$levels) = each %health ) { my @ascending = sort {$a <=> $b} @$levels; print "$patient: @ascending\n"; } for my $patient ( keys %health ) { my $levels = $health{$patient}; my @descending = sort {$b <=> $a} @$levels; print "$patient: @descending\n"; }
    Output:
    John Kay: 128 151 Sally Gi: 145 174 John Kay: 151 128 Sally Gi: 174 145
      Appreciate the response.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1025827]
Approved by igelkott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (15)
As of 2014-08-20 09:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (108 votes), past polls