I am new to Perl and in the process of learning.

I wrote a simple script to check two networks to see if the other hosts on those networks are up. I am sure that there is a better and more elegant way to do this. I'm open to any suggestions and/or pointers.

Here is what I have so far that is working. It's running on a Linux system if that matters.

#!/usr/bin/perl -w use strict; my $hostfile = "/etc/hosts"; my $pattern0 = "192.168"; my $pattern1 = "172.16"; my $eth_card0 = "eth0"; my $eth_card1 = "eth1"; chomp(my $ipaddr0 = `ifconfig | awk '/$eth_card0/ {getline; print}' | +awk '{print \$2}' | cut -d: -f2`); chomp(my $ipaddr1 = `ifconfig | awk '/$eth_card1/ {getline; print}' | +awk '{print \$2}' | cut -d: -f2`); open INPUT, '<', "$hostfile" or die "Cannot open $hostfile $!"; while (<INPUT>) { chomp; if ((/$pattern0/) or (/$pattern1/)) { my @hosts = split(" ", $_); foreach my $hosts (@hosts) { if (( $hosts =~ $pattern0 ) && ( $hosts ne $ipaddr0 ) || ( $hosts =~ $pattern1 ) && ( $hosts ne $ipaddr1 )) { pingip($hosts); } } } } close INPUT; sub pingip { my $rhost = $_[0]; my $retval = ""; system("ping -c 1 $rhost > /dev/null"); if ( $? != 0 ) { print "$rhost is not up\n"; } else { print "$rhost is up\n"; } }

My specific questions are first and foremost, is there a better way to do this? Second, can some of you that know more about Perl than me point out some of the errors that I might have made?

This script isn't anything that is real important to me, I'm simply using it as a learning tool mainly on working with arrays, and eventually hashes.

Thank you in advance for your help


In reply to How do I check the status of a remote network by at2marty

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.