kingjamesid has asked for the wisdom of the Perl Monks concerning the following question:

When I run this, it says everything is goodhostname. Something wrong with regex?
@hostnames = qw(goodhost badhost); foreach (@hostnames){ @a = `ping $_`; print "$_ is Alive\n" if @a =~ (/please check/); }

Replies are listed 'Best First'.
Re: Ping host
by almut (Canon) on Oct 27, 2009 at 20:34 UTC

    =~ 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.

      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.
Re: Ping host
by toolic (Bishop) on Oct 27, 2009 at 20:31 UTC