10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 6 ■ NET:: TOOLS 131When called in scalar context, the ping() method returns 1 for success or undef for a failure(an unsuccessful ping). When called in a list context, the ping() method returns the success flag(1 for success), the time that the operation <strong>to</strong>ok, and the IP address used.When run, the program produces output like this:Host www.google.com (64.233.167.104) responded in 0 secondsThe time returned by ping() is sent in integer format by default. This means that, manytimes, the time will be integer 0, since the ping operation <strong>to</strong>ok less than a second. To obtainmore accurate times, use the Time::HiRes module, as described in the next section.The final section of the example evaluates the $status variable. If the $status variable is1, the ping was successful and the results are printed. If the $status variable is 0, the ping wasunsuccessful and the corresponding result is also printed.Getting More Accurate TimesAs previously stated, the time returned by ping() is returned in integer seconds. This is fine if allyou’re looking for is success or failure of the ping operation as a whole. However, if you want <strong>to</strong>obtain more accurate times, you need <strong>to</strong> use the Time::HiRes module, available from CPAN. Thecode in Listing 6-16 (Pingex2.pl) is essentially the same as Listing 6-15, with two exceptions: theTime::HiRes module is brought in<strong>to</strong> the namespace, and it includes a call <strong>to</strong> the hires() methodon the ping object.Listing 6-16. A Ping Using Time::HiRes for More Accurate Times#!/usr/bin/perl -wuse Net::Ping;use Time::HiRes;use strict;my $pingobj = Net::Ping->new('icmp');my $host = "www.google.com";$pingobj->hires();my ($status,$time,$ip) = $pingobj->ping($host);if ($status) {print "Host $host ($ip) responded in $time seconds\n";} else {print "Host $host ($ip) unreachable\n";}When run, the program produces output similar <strong>to</strong> that shown here:Host www.google.com (64.233.167.104) responded in 0.0691518783569336 seconds

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!