Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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
Replies are listed 'Best First'.
Re: Push Function and Hash
by tangent (Priest) 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"; }
    John Kay: 128 151 Sally Gi: 145 174 John Kay: 151 128 Sally Gi: 174 145
      Appreciate the response.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (9)
As of 2016-05-26 17:11 GMT
Find Nodes?
    Voting Booth?