Walt Mankowski on Thu, 18 Apr 2002 09:07:57 -0400


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Perl Advisor: Doing Many Things, Like pings


On Thu, Apr 18, 2002 at 08:32:11AM -0400, Chuck Peters wrote:
> 
> An article by Randal L. Schwartz on UNIX Review
> http://www.unixreview.com/documents/s=2426/uni1018362725458/0204g.htm
> has a script for checking a subnet to see if host up and responding to
> pings.  Script is also at http://ccil.org/~cp/perlping
> 
> I tried the script and its saying every IP on the subnet is up, which
> isn't the case as I have 4 IP's on this LAN.  The script seems to be
> failing at the test of:
> 
> sub ping_a_host {
>   my $host = shift;
>   'ping -i 1 -c 1 $host 2>/dev/null' =~ /0 packets rec/ ? 0 : 1;
> }
> 
> Because I don't use perl frequently I don't understand the syntax and have
> a hard time reading it.  What does the "=~ /0 packets rec/ ? 0 : 1" part
> do?  Why is the test failing?

It looks like you entered single quotes when you should have entered
backquotes.  Try it this way:

sub ping_a_host {
  my $host = shift;
  `ping -i 1 -c 1 $host 2>/dev/null` =~ /0 packets rec/ ? 0 : 1;
}

Backquotes run the command inside the quotes, waits for it to
complete, and return the output.  The =~ is perl's regex operator.
The ? : is stolen from C.  $a ? $b : $c is a shorthand way of saying

if ($a) {
   $b;
} else {
   $c;
}

There's not "return" statement in that sub.  That's a another Perl
shorthand.  If a sub doesn't have an explicit return statement, it
returns the last expression evaluated.  So in this case, it will
return either a 0 or 1, depending on whether it finds that regex in
the output of ping.

So what that line means is:

Run the ping command and wait until it exits.
If the output of ping contains the phrase "0 packets rec",
  return 0.
Otherwise,
  return 1.

Walt

Attachment: pgpX1ImMdeSZv.pgp
Description: PGP signature