in reply to Ping host

=~ binds a scalar expression to a pattern match.  So you could do "@a" =~ ... (which would interpolate the array's contents into a string (space-separated)), or simply assign what the backticks return to a scalar variable (instead of an array) in the first place.

Replies are listed 'Best First'.
Re^2: Ping host
by kingjamesid (Acolyte) on Oct 28, 2009 at 15:48 UTC
    use warnings; @hostnames = qw(goodhost badhost); foreach (@hostnames){ @a = `ping $_`; print "for $_ checking....."; if ("@a" =~ /please check/){ print " For $_ : host not available."; } check/; }
    All I wanted to say: badhost : host not available But doesnt work

      Maybe you want to check case-insensitively, i.e. /please check/i

      The ping on my Windows box outputs for example:

      Ping request could not find host badhost. Please check the name and tr +y again.

      Some notes:

      • also add use strict, please
      • line 11: check/ certainly fails to parse
      • check your OS documentation on you flavour of ping: you may be able to use the return code on e.g. Unix or Cygwin: system("ping -c3 $host"); warn if $?;
      • why @a=`` and "@a"=~ // instead of the simpler $a=`ping -c3 host 2>&1` or similar?
        I use 2?&1 to include output on stderr instead of just stdout; this might be part of your problem or just me subscribing to an overly cautious cargo-cult :).
      • finally there's also Net::Ping

      Resulting in e.g. this example, which should also run on e.g. cygwin:

      use strict; use warnings; my @hostnames = qw(www.leo.org dhbvg.xxx); foreach (@hostnames){ # my $a = `echo pinging $_ 1>&2 ; ping -c3 $_ 2>&1 | tee -a /dev/tt +y`; my $a = `ping -c3 $_ 2>&1`; if ($a =~ /unreach|unknown host/i){ print " For $_ : problems: $a."; } }
      cu & HTH, Peter -- hints may be untested unless stated otherwise; use with caution & understanding.
        I use 2>&1 to include output on stderr instead of just stdout

        Though this is generally a good idea, the native Windows ping (which is the only one known to me to ever output "Please check...") appears to write to stdout. I.e., this works fine for me:

        perl -le "print `ping badhost` =~ /please check/i ? 'bad':'good'"