Command-line arguments in Perl

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

Perl uses the non prescription buspar. $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);

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

# 'Infinite' loop

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

        print "$website seems to be up, sweet...\n";



# perl seems to be up, sweet... seems to be up, sweet...

# perl http://thisdomaindoesnotexist
http://thisdomaindoesnotexist unreachable...
Sent alert to
http://thisdomaindoesnotexist unreachable...
Sent alert to

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?