Feed on

Archive for the 'Perl' Category

to get the last element of an array in perl, use the length of the array as your index. for instance, if my array is very creatively named “my_array,” the length of the array is: $#my_array and it’s last element is $my_array[$#my_array]

convert a string into an array in perl

to convert a string into an array of characters: $string = “a very nice string”; @char_array = split(”,$string);

trying to push values onto my hash of arrays (push($hash{$key},value);), i kept receiving the following error: Type of arg 1 to push must be array turns out i needed to explicitly cast my hash value as an array, using @{}: push(@{$hash{$key}},value);

count matches in perl

say you’d like to count the number of times you match a string in perl.  there’s a quick and easy way to do it using the ‘tr’ function.  for instance, to count the number of ‘a’s in a string: $_ = “asdfasdfaf”; $match_count = tr/a/a/; note that what you’re actually doing is counting the number […]

glob is perl’s version of “ls”: it’ll list all of the files in a directory that match the criteria you set forth.  i’ve used it here to help me iterate through all of the files in a directory that end in “.phy”.  i specify this directory as a command line argument [$ARGV[0]]. #!/usr/bin/perl use warnings; […]

append in perl

to append in perl, use the append operator “.=” for instance: a = “vam”; a .= “pire”; print a;  # yields “vampire”

get the length of a perl array

perl sometimes is just too easy. so easy that it’s confusing. for instance, to print the length of an array @my_array, you don’t need a length command or anything. instead, just code: print @my_array; (no way i’m ever going to remember a command that simple.)

generate a random number in perl

the rand() function will return a value drawn from the uniform distribution. rand() alone returns a value from (0,1). rand(x) returns a value from (0,x).

clear the screen in perl

to clear the terminal screen in a perl script, command: system(“clear”);

to read in a file and print its contents (filename specified as the first command-line argument): my($my_file) = $ARGV[0]; open(MYFILE,$my_file); while () { print $_; }

« Prev - Next »