Search code examples
perlfile-iopipefilehandler

How can get a filehandle for a Perl program's output?


I have an encrypted file X1, I have a Perl program P1 that decrypts the X1. I am parsing the decrypted file using a Perl program p2.

X1--P1(decrypter) --> X2(plain text file) --p2(parser) --> parse output

My parser is based on XML::Parser. It can work with a filehandle to the decrypted file. Now I am getting the X2 and storing it in the file system and reading it in the P2 and parsing it. Is there way I can directly get the filehandle over the P1's output and use that filehandle in the P2 to parse it directly with out requiring a temporary file?


Solution

  • Say you're using very weak encryption:

    #! /usr/bin/perl
    
    print <<EOXML;
    <doc>
      <elem attr="Hello, world!" />
    </doc>
    EOXML
    

    Using open $fh, "-|", ... will create a pipe connected to the standard output of a child process:

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    open my $decrypted, "-|", "./decrypt"
      or die "$0: open: $!";
    
    while (<$decrypted>) {
      print "got: $_";
    }
    

    Output:

    got: <doc>
    got:   <elem attr="Hello, world!" />
    got: </doc>