Capturing output with perl

I have a number of pet hates when it comes to coding. Amongst these is the use of temporary files to capture the output of commands being executed from perl.

  1. system(‘ls -1 > ls.log’);
  2. open LOG, ‘ls.log’ or die ‘erm, error!’;
  3. while (<LOG>)
  4. {
  5.   # parse output
  6. }

Above is a very short example of the code I see people writing. I dislike the use of system() as I have seen it produce unexpected results in a win32 environment when you call your perl script from a non-standard command shell. I’m not overly keen on the use of the open command and file globs. I prefer to use the IO::File package and, rather than use a temporary file to capture the output, I pipe the output allowing my code to parse it as it is produced.

  1. use IO::File;
  2. my $fh = IO::File->new( "ls -1 2>&1 |" );
  3. if ($fh)
  4. {
  5.   while (defined (my $line = <$fh>))
  6.   {
  7.     # parse ouput
  8.   }
  9.   $fh->close;
  10. }
  11. else
  12. {
  13.   die "Error executing command";
  14. }

Using the above code, I have no temporary files and do not have to wait for the command to finish in order to parse the output.

No related posts.

Leave a Reply

You must be logged in to post a comment.