Feed on
Posts
Comments

Archive for the 'Perl' Category

let’s say you’ve got a string and you’d like to count the number of times some substring appears in it. let’s also assume that you’re lazy and you don’t want to leave your shell terminal to do it.  fortunately, there’s an easy way to count string matches from the command-line using a perl one-liner.   let’s […]

if you’re getting either the error: “Storable object version 2.13 does not match $Storable::VERSION 2.15″ or “Fink could not load the perl Storable module, which is required in order to keep a cache of the package index. You should install the fink “storable-pm586″ package to enable this functionality,” you’ll need to upgrade or install the […]

basic perl file input and output:

an example of how to read in the contents of a file and then write them out, in perl open(INPUT,$ARGV[0]); open(OUTPUT,”>$ARGV[0].out”); while (<INPUT>) { print OUTPUT $_; } close(INPUT); close(OUTPUT);

perl remove a directory

to remove a non-empty directory in perl: use File::Path; rmtree(“./temp_dir”);

randomize an array in perl

here’s one legitimate way to randomize an array in perl: # fisher_yates_shuffle( \@array ) sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; –$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } thanks perl cookbook!

how to hash a hash in perl

if my loathing of perl was measured in people, that loathing would be china. for instance, nesting a hash within another hash in perl is needlessly complex: first, you need to stick these dumb backslashes in front of your hash variables: my %return_vals; $return_vals{“hgt”} = \%hgt_list; $return_vals{“dup”} = \%dup_list; $return_vals{“los”} = \%los_list; recovering these hashes […]

to read in an input file and convert its characters into a matrix: open(SEQS,”$my_file”); my @aas; while() { chomp; @this_seq = split; push(@aas,[@this_seq]); }

passing a filehandle to a subrouting in perl is slightly tricky; you’ll need to use  an asterisk.  for instance: open (F, “/tmp/sesame”) || die $!; read_and_print(*F); sub read_and_print { local (*G) = @_;  # Filehandle G is the same as filehandle F while () { print; } }

get size of hash in perl

getting the size of a hash is slightly non-intuitive in perl: print “my hash size is: ” . keys(%my_hash);

last element of an array in perl

perl indexes from the back using negative numbers.  so to get the last element of @array: $array[-1]

Next »