IzziD code logo

Topics

Home

Bioinfo

Web

Misc

About

Other IzziDs

IzziDassorted

IzziDtravel

IzziDwetlab

IzziD

How to assign standard out (STDOUT) to a variable in Perl

Article created: Aug 21, 2011
Article by: Jeremiah Faith

Sometimes its convenient to assign filehandles to variables in Perl. Whereas we’d typically open and write to a file in Perl like this:

my $outfile = "out.txt";
open(OUT, ">$outfile") or die "can't open $outfile: $!\n";

print OUT "here is my output\n";

It can often be more flexible and powerful to use normal Perl variables for the file handle:

my $outfile = "out.txt";
my $out;
open($out, ">$outfile") or die "can't open $outfile: $!\n";

print $out "here is my output\n";

Using variables like this makes it pretty easy to for example create arrays or hashes of filehandles, while making your code still somewhat readable (at least as readable as you’d expect for Perl). But what do you do if you need to assign a built-in filehandle like STDOUT or STDERR to a filehandle? Do the following:

my $out = *STDOUT;

print $out "here is my output\n";

This assigns $out a reference to the typeglob for STDOUT. The same method should work for STDERR or any other user-defined file handles that aren’t initially assigned to a variable.

my $outfile = "out.txt";

open(OUT, ">$outfile") or die "can't open $outfile: $!\n";
my $out = *OUT;

print OUT "here is my output\n";
print $out "here is more output\n";