Tuesday, May 1, 2007

My First useful PERL program

#!/usr/bin/perl -w

$username = $ARGV[0];
$username = "s28arunpbk" if(!$username);
#
# Get the username from the first command line argument
# If null assign my user id.
#

use LWP;
use LWP::UserAgent;
#
# Initialize objects
#


$ua = LWP::UserAgent->new;
$ua->agent("Checkmap/1.0");
my $req=HTTP::Request->new(GET => "http://sitemeter.com/?a=stats&s=$username&r=0");

my $res = $ua->request($req);
#
# Send a request and grab the response...
#

if($res->is_success)
{
$contents = $res->content;
$contents =~ m/<title>(.*)<\/title>/i; #regexp to find the title
if($1 =~ m/Site Meter/)
{
print "Wrong User name!\nAborting\n";
exit 0;
#
# If the web page title contains the words "Site Meter",
# it means the username was invalid and got redirected to
# index.
#

}

print "$1\n","="x length $1,"\n";

#
# Print the title and draw an underline...
#


$contents =~ s/ //g; #Strip `&nbsp;`
$contents =~ s/\<.*?\>//g; #Strip all HTML tags
$contents =~ s/\s+//g; #Strip all spaces
$contents =~ m/Total(([0-9]|,)+)Average/g; #The data we need.

print "Visits : ",$1;

$contents =~ m/Total(([0-9]|,)+)Average/g;
printf "\nPageviews : $1\n";
}
else
{
print "Error : $! ",$res->as_string;
exit 1;
#Messed up somewhere.
}
exit 0;
#thats all


What does this do ?

The script gives me the total number of visitors and pageviews on my site via sitemeter.com. By passing an optional username as a command line argument you can get the same information of that account.

How to use ?

Check whether you have Perl installed on your computer.
Start a command prompt and type perl -v, if the command is not found download and install Perl.

Copy the source code given above and paste it in a new file say dstat.pl
Run the code by perl dstat.pl.

1 comments:

Arun Prabhakar said...

I no longer use sitemeter.com beacuse of this reason ...
But you can use script for similar uses by a few tweaks, so i have left it here...

Keep visiting for latest scripts ....