#!/usr/local/bin/perl # Jaime Prilusky, 2009 # data from http://www.genomesize.com/ # initialize a 'mammals' hash with key-value pairs my %mammals = ( "Ornithorhynchus anatinus" => 54, "Tachyglossus aculeatus" => 64, "Gorilla gorilla" => 48, "Homo sapiens" => 48, "Pan troglodytes" => 48, "Pongo pygmaeus" => 48, ); # extract single value from a hash. Print the value for 'Homo sapiens' print "\n"; print "Homo sapiens diploid chromosome number is ", $mammals{'Homo sapiens'}, "\n"; # get and print all keys print "\n"; my @keys = keys %mammals; print "All keys are: @keys\n"; # get and print all values print "\n"; my @values = values %mammals; print "All values are: @values\n"; # print the entire hash, no sort print "\n"; while(($specie,$diploidNumber) = each %mammals) { printf ("%30s %d\n",$specie,$diploidNumber); } # print the entire hash, no sort print "\n"; foreach $specie (keys %mammals) { my $diploidNumber = $mammals{$specie}; printf ("%30s %d\n",$specie,$diploidNumber); } # print the entire hash, sorted by specie print "\n"; foreach $specie (sort keys %mammals) { my $diploidNumber = $mammals{$specie}; printf ("%30s %d\n",$specie,$diploidNumber); } # print the entire hash, sorted by diploid number print "\n"; foreach $specie (sort {$mammals{$a} <=> $mammals{$b}} keys %mammals) { my $diploidNumber = $mammals{$specie}; printf ("%30s %d\n",$specie,$diploidNumber); }