A backticks-style system call to get the date

The foreach loop works on the list returned by the backticks-style system call that invokes a basic niscat report. Each line is split at space separators; only the first three elements are required from the line, and these are obtained by assignment to an lvalue list – ($name, $alias, $ip) = split / /. The name string must again be split, at ‘.’ separators, to extract machine name and department name. Finally, these data are inserted into the data structure (note the ‘double hash indexing’ for the hash of hashes): $machines{$dept}{$machine} = $ip.

#!/share/bin/perl
   $date = `date`;
   $str = "Today is $date";
   print $str , "\n";
   foreach (`niscat hosts.org_dir`) {
   ($name, $alias, $ip ) = split / /;
   if($name =~ /^(\w+)\.(\w+)/) {
   $machine = $1;
   $dept = $2;
   $machines{$dept}{$machine} = $ip;
   }
   }
   foreach $dept (keys %machines) {
   print "$dept\n";
   foreach $machine
   (keys %{ $machines{$dept} } ) {
   $ip = $machines{$dept}{$machine};
   printf "\t%-20s\t%16s\n" ,$machine, $ip;
   }

The second foreach loop simply runs through the keys of the first hash, i.e. the department names.

Programming

The inner loop picks out the machine names associated with each department and prints machine name and IP address. The expression { $machines{$dept} } selects the hash that is the value associated with the key $dept in the main %machines hash structure. The final report generated will be in the desired format:

accounting
   red 209.208.207.1
   blue 209.208.207.2
   ...
   sales
   jabberwok 209.208.207.46
   ...

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>