tags:

views:

91

answers:

1

Out of curiosity, is it possible to create, instantiate, or otherwise access additional output buffers besides STDOUT and STDERR from within a Perl script?

The use case would be additional outputs to pipe in to files or other commands, eg ./doublerainbow.pl 3>full_on.txt 4>all_the_way!.txt

+7  A: 

Absolutely. The open command with the >& mode allows you to open filehandles on arbitrary file descriptors.

# perl 4fd.pl > file1 2> file2 3> file3 4> file4 5< file5

open STDFOO, '>&3';
open STDBAR, '>&4';
open STDBAZ, '<&5';   # works for input handles, too

print STDOUT "hello\n";
print STDERR "world\n";
print STDFOO "42\n";
print STDBAR <STDBAZ>;

$ echo pppbbbttt > file5
$ perl 4fd.pl >file1 2>file2 3>file3 4>file4 5<file5
$ cat file1
hello
$ cat file3
42
$ cat file4 file2
pppbbbttt
world
mobrule
Of course, if you go around calling handles `STDFOO` it kind of cheapens the whole "std" thing. :)
hobbs
hobbs is right but I think mobrule was trying to point out that STDOUT and STDERR are just synonyms for output on fd1 and fd2 out of the box, but even that can be changed, it's not too uncommon to within a script point STDERR to another fd for a file that's been opened for writing.
mikegrb