Printing Output

We have developed a custom subroutine that our script uses for printing output. We have done this because we have a command-line option (-o) that allows all output to be sent to an output file, so we can send everything through one subroutine that handles output to both the screen and a file, if necessary.

printReport subroutine

As we just mentioned, we use the printReport subroutine to manage the printing of output to both the screen and output file, if necessary. Let’s take a quick look at this routine’s contents:

sub printReport {
 my ($printData) = @_;
 if ($args{o}) { 
  open(REPORT, ">>", $args{o}) or die "ERROR => Can't write to file $args{o}\n";
  print REPORT $printData;
  close(REPORT);
 }
 print $printData;
}

As we mentioned, this routine is pretty simple. It takes one parameter as input (the data to be printed), appends the data to a file if the user specified the -o option ($args{o}), and prints the data to the screen. If the script cannot open the log file for writing, it dies and prints the error to the screen. Now all we have to do when we want to print something is send it to printReport, and we know it ends up printing in the right place(s). Now that we have finished the first subroutine, let’s go back to the main body of the script.

Get Network Security Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.