Perl – worth more than a pearl?

Its done. I knocked over my first perl script.

What did I learn? Are you kidding. What didn’t I learn! Ok, I learnt its not too bad once you know where you are going. Don’t get me wrong – it wasn’t the most complex script so there is plenty more to learn but its a starting point.

Here are some things I picked up or used:

#!/usr/bin/perl
^- Important.


my $host=$ARGV[0];
my $url=$ARGV[1];

^- Grabbing arguments – pretty standard stuff there


my ($b_s, $b_usec) = gettimeofday;

^- Getting the time – I used this to calculate the latency it took to grab a page. Archaic method maybe – but works for my purposes.


my $www=WWW::Mechanize->new(
agent => 'MasterBlaster-01',
);

# Grab the page specified as ARG1 or bomb out
$www->get($url) or print "Cannot retrieve $url\n" and exit($return);

# Dump the page to a string without html tags
my $stupidstring=$www->content('format' => 'text');
# Match on host name provided - then grab the next digits and store as error numbers
if($stupidstring =~ m/$host([0-9]+).*$host([0-9]+)/){
$DailyErrors=$1;
$HourlyErrors=$2;
$return=$ERRORS{'CRITICAL'};
}else{
# If we can't get the URL - bomb out with a critical error
print "Cannot retrieve $url\n";
$return=$ERRORS{'CRITICAL'};
exit($return);
}

^- This was the replacement method I used to grab the page I needed to check – forget the errors args, this won’t mean much to anyone externally. The previous method was simply dumping the entire page – html tags and all – which caused problems as you had to deal with ALL THESE TAGS. Urg.


# Get time of day now - calculate how long it took
my ($a_s, $a_usec) = gettimeofday;
my $diff=0;
if($b_s == $a_s) {
$diff = $a_usec - $b_usec;
} else {
$diff = 1000000 - $b_usec; $b_s += 1; $diff += $a_usec; $diff += ($a_s - $b_s)
* 1000000;
}
$diff /= 1000; $diff = int($diff);
alarm(0);

^- The rest of the latency calculating code – this is something pretty standard we use across a number of scripts…. does the job.


# Check the error tallys against the thresholds specified below
# return the error tallys and latency figures along with an error code
if ($HourlyErrors > 20) {
print "CRITICAL: ${diff}ms - (day: $DailyErrors, hour: $HourlyErrors)\n";
exit($ERRORS{"CRITICAL"});
} else {
if ($HourlyErrors > 10) {
print "WARNING: ${diff}ms - (day: $DailyErrors, hour: $HourlyErrors)\n";
exit($ERRORS{"WARNING"});
} else {
print "OK: ${diff}ms - (day: $DailyErrors, hour: $HourlyErrors)\n";
exit($ERRORS{"OK"});
}
}

^- Checking my results against specific thresholds and then returning a state to the monitoring system. The monitoring system then takes specific action based on this result.

Essentially it does 2 things – grabs a page, regex for a string which gives a value, calculates latency to get the value and then depending on the value returns a state!

</fear of perl>

Fun fun fun!

Comments are closed.