Below is a list of useful code snippets. All are written by me, unless specified otherwise.
If something looks broken, just let me know. I am also open to alternative (clever!) solutions.
# change ChRiS into Chris
print ucfirst(lc("ChRiS")); # prints Chris
# stick a comma delimited file into a multidimensional array
# won't work if a record has a comma in it, like "foo\, bar"
# there is a Text::CVS
open FH, ">file" or die "open: $!";
my @data;
while (local $_=) {
push @data, [ split /,/ ];
}
# remove both leading and trailing whitespace for a string
s/^\s+//, s/\s+$// for $string;
# or for an entire array/list/file
s/^\s+//, s/\s+$// for @array;
# return highest number in a list
sub max {
return (sort { $a <=> $b } @_)[-1];
}
# return true if a string (or list) has a non-word character in it
sub match_word { return grep { /\W/ } @_ }
# change every instance of "foo" in a file into "bar" (great for editing bind zone files!)
perl -i.bak -pe's/foo/bar/' filename
# make sure the first word of each line in a file has an uppercase letter if it starts with a letter
perl -i.bak -pe's/\s*([a-z])/\u$1/'
# simple way to do factorials
sub factorial {
my $number;
$number =~ s/!$//; # remove trailing ! just in case
return eval join "*", 1..$number;
}
# round a number (not perfect - try rounding 4.49999999999999999 - it turns into 5)
sub round {
return int($_[0] + .5);
}
# round to a certain number of places
sub round {
my ($num $places) = @_;
$places ||= 0; # play nice with the warnings pragma
return sprintf "%${places}f", $num;
}
# random whole number between 1 and 10
# I tested the distribution with this:
# perl -wle'my %nums; for (1..1000000) { $nums{int(rand(10)) + 1}++ } print "$_ => $nums{$_}" for sort { $a <=> $b } keys %nums'
# the numbers seem random enough. Use Math::TrulyRandom for truly random numbers, or search cpan
print int(rand(10)) + 1;
# count occurances of something(s)
sub mode {
my %counter;
for my $item (@_) {
$counter{$item}++;
}
# now print $counter{foo} will print how many occurances of "foo" there are
return %counter;
}
# print the time
print scalar localtime;
# store the time away in a variable
my $time = scalar localtime;
# print the month
print +(split / /, scalar localtime)[1];
# print month day, year
my ($month, $day, $year) = (split / /, scalar localtime)[1,2,4];
print "$month $day, $year";
perldoc -f localtime to figure out other ways of doing this.