Command-line arguments in Perl

Command-line arguments are very useful when you, for example, want to pass arguments to background processes. This example demonstrates a process which monitors a website and sends alerts if the website is unreachable.

Perl uses the $ARGV variable for storing command-line arguments.

#!/usr/bin/perl -w
# Monitors a website to see if it's up and
# sends an e-mail message if the website is unreachable

use strict;
use LWP::Simple;
use Net::SMTP;

# Check website every 10 seconds
my $interval = 10;

# The website passed as a command-line argument
my $website = $ARGV[0];

# Who do we need to send the alerts to?
my $alertTo = $ARGV[1];

if(!$website || !$alertTo){
    die("Check your arguments!");
}

sub sendAlert(){

    print $website." unreachable...\n";

    my $mailHandle = Net::SMTP->new('localhost', Timeout => 2);

    if($mailHandle){
        $mailHandle->mail('noreply@snipd.net');
        $mailHandle->to($alertTo);
        $mailHandle->data();
        $mailHandle->datasend("To: $alertTo\n");
        $mailHandle->datasend("Subject: Dude!\n");
        $mailHandle->datasend("\n");
        $mailHandle->datasend("I can't seem to reach $website...\n\nKind regards,\n\nUptime Genie");
        $mailHandle->dataend();
        $mailHandle->quit;
        print "Sent alert to $alertTo\n";
    } else {
        print "Could not send the alert!\n";
    }
}

# 'Infinite' loop
while(1){

    my $websiteContent = get $website;
    sendAlert() unless defined $websiteContent;

    if($websiteContent){
        print "$website seems to be up, sweet...\n";
    }

    sleep($interval);
}

Output:

# perl monitor.pl http://www.apple.com steve@apple.com
http://www.apple.com seems to be up, sweet...
http://www.apple.com seems to be up, sweet...

# perl monitor.pl http://thisdomaindoesnotexist fy@snipd.net
http://thisdomaindoesnotexist unreachable...
Sent alert to fy@snipd.net
http://thisdomaindoesnotexist unreachable...
Sent alert to fy@snipd.net
This entry was posted in Perl and tagged , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?