It was Friday, February 21, 2003 when Bryan Harris took the soap box, saying:
: 
: I'm writing a simple script (qstat) to sum, count, and average whatever stream of 
numbers the user throws at it.
: 
: It loops through @ARGV reading files, so it works fine if I say:
: 
:   qstat somefile someotherfile
: 
: However I'd like to be able to do:
: 
:   awk '{print $1}' somefile | qstat
: 
: This doesn't work.  How do I accept input from a pipe?

[snip]

: # loop through files
: foreach $file (@ARGV) {
: 
:   open(FILE, $file) || die("Couldn't open $file: $!\n");
:   $_ = <FILE>;      
:   close(FILE);
: 
:   @nums = split;
:   foreach (@nums) {
:     if (/^[\d\.\-\+]/) {
:     $sum += $_;
:     $count++;
:     ($_ > $max) && ($max = $_);
:     ($_ < $min) && ($min = $_);
:     }
:   }
:   
: }

[snip]

The above loops, and your pipe problem can be simplified with the
following:

while ( <> ) {
  if (/^[\d\.\-\+]/) {
    $sum += $_;
    $count++;
    ($_ > $max) && ($max = $_);
    ($_ < $min) && ($min = $_);
  }
}

'<>' is magical, it will loop over lines that are passed in, and when
files are supplied on the command line, they are opened and looped
through as well.  It's an ever so handy feature.  Plus, it's low on
memory.


  Casey West

-- 
Shooting yourself in the foot with Snobol 
If you succeed, shoot yourself in the left foot. If you fail, shoot
yourself in the right foot. 


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to