Friday, January 14, 2011

Perl Cheat Sheet

Inhale the contents of a file:

open (TABFILE,"$filename") || die "Can't Open $filename: $!\n";
@LINES=<TABFILE>;
chomp @LINES;
close(TABFILE);

Open for add

open (TABFILE,">>$filename") || die "Can't Open $filename: $!\n";

Open for write entire file (destroys existing file)

open (TABFILE,">$filename") || die "Can't Open $filename: $!\n";

Iterate over a hash array

while (($hashkey,$hashvalue) = each %hasharray) {
print TABFILE "$hashvalue\n";
}

Number of elements in an associative array
$count = keys %tabhash; 

Sort a hash array by keys

foreach $key (sort keys %tabhash) {
print "<option value=$script?s0=$key> $trans{$key}\n";
}


Sort a hash array (associative array) by values
First, you need a sort subroutine

Use this subroutine if you are sorting a numeric key
sub Hashvalue {
$data{$a} <=> $data{$b};
} #hashvalue
Use this subroutine if you are sorting a character key
sub Hashvalue {
$data{$a} <=> $data{$b};
} #hashvalue

Then run the sort. Remember to define the sort 
before you use it and don't use the & on 
the subroutine name. It won't work. Also, once 
you have the key from the next sorted value you
need to acquire the data.

Code for iteration: Remember to replace the word data with your hashname on both the sort and the iteration code
foreach $hashkey (sort Hashvalue (keys(%data))){
$hashvalue = $data{$hashkey}; 

Code goes here

} #foreach 

No comments: