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

The following script pings a bunch of addresses. If it fails it writes to file "miss" which works fine. The problem is if I use this file "miss" in another perl script i.e. open, and do "if exists" against hash with its contents it always fails if. however I can use vi and write the exact same content and the script works! What mystery characters are being passed? See earlier question from this morning (read value from file won't pass if exists??). Second script at bottom. this reads miss and compares to hash.
#!/usr/bin/perl -w my $dir="/home/lcollins"; system "/bin/cat /dev/null > $dir/miss"; open (HOSTS,"$dir/ClockIP") or die "Can't open HOSTS $!"; open (MISS,">>$dir/miss") or die "Can't open miss $!"; my $miss=<MISS>; while (<HOSTS>) { chomp; @args = ("/bin/ping $_ -c 2"); system(@args) == 0 or print MISS "$_\n" } print "Done.";
Look in hash for stuff from miss. (sorry for all the code).
#!/usr/bin/perl -w my $dir="/home/lcollins"; open MISS, "$dir/miss" or die "can't open $!"; %clocks=( "start"=>"000", "10.1.0.15"=>"0", "10.20.20.13"=>"1FL Sadlier", "10.20.11.15"=>"Convent", "10.20.44.15"=>"1 Cooke", "10.20.44.16"=>"2 Cooke", "10.20.46.36"=>"6 Cooke", "10.20.46.37"=>"4 Cooke", "10.20.46.38"=>"5 Cooke", "10.3.0.15"=>"Beacon", "10.3.0.16"=>"Beacon", "10.4.0.15"=>"9G", "10.6.0.15"=>"Comm Diss", "END"=>"000" ); my $miss=<MISS>; #chomp $miss; #print "Before loop $miss\n"; foreach (<MISS>){ chomp; #print "in loop $_ \n"; if (exists $clocks{$_}){ print "$_ is down\n"; } close MISS; }

Replies are listed 'Best First'.
Re: Print to a file then use file content for test?
by osunderdog (Deacon) on Jan 04, 2005 at 22:27 UTC

    In your first code block, you should probably close MISS after you are done looping through HOSTS This might be the problem. The file won't get flushed and closed until the script exits...

    In the second block of code, it looks like you are pulling off the first line into $miss but aren't using $miss later (References to it are commented out.) You should probably comment that line out.


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

      In addtion to the problems osunderdog pointed out,

      1) It's better to use while (<MISS>) (which reads the file one line at time) than foreach (<MISS>) (which loads the entire file into memory for no reason).

      2) You don't need my $miss=<MISS>; in the first script either. Why are you reading from a file you opened for write-append?

        Thanks for the input I'll make those corrections. Any ideas on the difference between a file I write and one generated by my first script?
      Update Monks: I moved this code to a solaris box and it works fine! The box it is running on now is a linux machine. Any Linux gurus out there seen this?
        please ignore the section on it working on Solaris. it does not work on solaris either.