Lecture Code: Perl V: Hashes

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
 
## create a hash all at once
my %genetic_code = (
 "ATG" => "Met",
 "AAA" => "Lys",
 "CCA" => "Pro",
);
 
## print a singe key/value pair
print "Before/ATG: " , $genetic_code{"ATG"} ,"\n";
 
##print out the entire hash one key/value pair at a time
foreach my $codon (keys %genetic_code){
   ## get, or retrieve, a value using a key
   my $aa = $genetic_code{$codon};
   print "$codon translates to $aa\n";
}
 
## overwrite or reset a single key's value
$genetic_code{"ATG"} = "start_codon";
 
## print a single/key value pair after reset
print "After/ATG: " , $genetic_code{"ATG"} ,"\n";
 
## print the entire hash after reset
foreach my $codon (keys %genetic_code){
   my $aa = $genetic_code{$codon};
   print "$codon translates to $aa\n";
}
 
## what are other ways to print out an entire hash?
## in and outside of quotes is useless:
print "---other ways to print out an entire hash---\n";
print "Printing the hash within quotes does not work: %genetic_code\n";
print "Printing outside of quotes is swished and pretty useless: ", %genetic_code,"\n";
 
## Data::Dumper is useful for debugging
print "Print hash using the module Data::Dumper:\n";
## make sure to use the '\' before '%'. can also use to print arrays: \@array
print Dumper \%genetic_code , "\n";
tab_parser.pl
#!/usr/bin/perl
use strict;
use warnings;
 
my $file = shift @ARGV;
open (INFILE, '<', $file)
or die "can't open file $file $!\n";
my %hash;
while (my $line = <INFILE>){
  chomp $line;
 
  ## this works!!
  ## split on tabs and store the value of the first column in a single line to $key.
  ## this is inside of a while, so this will repeat for every line. 
  ## this will ignore every column past the second column
  #my ($key, $value) = split /\t/, $line;
  #$hash{$key} = $value;
 
  ## this works!!
  ## 
  #my @array = split /\t/, $line;
  #print join ('--',@array), "\n";
  ## use the 0th element as the key and the 2nd element as the value
  #$hash{$array[0]} = $array[2];
 
   ## this works!!
   ## this assigns the first three columns to variables
   ## uses the $animal as the key and $food as the value. $count is not used here
   my ($animal,$count,$food) = split /\t/, $line;
 
   $hash{$animal} = $coat;
}
 
## print out the entire hash one key/value pair at a time
foreach my $key (sort keys %hash){
        my $value = $hash{$key};
        print "key:$key value:$value\n";
}
tab.2col.txt: tab-delimited file with 2 columns
geneA	ATGC
geneB	GCTA
geneC	AACT
tab.3col.txt: tab-delimited file with 3 columns
cat	2	cat food
dog	4	cats
ferret	10	cat food
bird	15	seeds

Comments are closed.