11

I am executing a Perl program. Whatever is being printed on my console, I want to redirect that to a text file.

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
Cindrella
  • 1,671
  • 7
  • 27
  • 47

4 Answers4

18

The preferred method for this is to handle redirection via the command line, e.g.

perl -w my_program.pl > my_output.txt

If you want to also include stderr output then you can do this (assuming your shell is bash):

perl -w my_program.pl &> my_output.txt
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • OK - see above edit - also take some time to learn command line basics for Linux etc. – Paul R May 21 '12 at 09:23
  • Thanks.... in file i have used open STDERR, '>output.txt'; close STDERR; its working.... – Cindrella May 21 '12 at 09:25
  • 2
    For future reference note that it's generally better to do the redirection on the command line - that way you don't need to modify your Perl code, and you can re-use it in different contexts without any changes. – Paul R May 21 '12 at 09:52
11

In the CLI you can use >, like this:

perl <args> script_name.pl > path_to_your_file

If you want to do this inside the perl script, add this code before you print anything:

open(FH, '>', 'path_to_your_file') or die "cannot open file";
select FH;
# ...
# ... everything you print should be redirected to your file
# ...
close FH;  # in the end
ArtMat
  • 2,110
  • 12
  • 24
  • 1
    well, if you have explicit prints to different filehandles, than you should follow the CLI way as advised by Paul R and this question probably should be tagged as `bash` or similar because it has little to do with Perl itself – ArtMat May 21 '12 at 09:59
6

On Unix, to capture everything that goes to your terminal, you want to redirect both the standard output and the standard error.

With bash, the command resembles

$ ./my-perl-program arg1 arg2 argn > output.txt 2>&1

The C shell, csh derivatives such as tcsh, and newer versions of bash understand

$ ./my-perl-program arg1 arg2 argn >& output.txt

to mean the same thing.

The syntax for the command shell on Windows resembles Bourne shell's.

C:\> my-perl-program.pl args 1> output.txt 2>&1

To set up this redirection in your Perl code, add

open STDOUT, ">", "output.txt" or die "$0: open: $!";
open STDERR, ">&STDOUT"        or die "$0: dup: $!";

to the beginning of your program’s executable statements.

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
3

If you want your output to be printed on console as well as logs then append this line to you code (e.g. before any print statements)

open (STDOUT, "| tee -ai logs.txt");
print "It Works!";

After last print in your script

close (STDOUT);

For error messages only,

open (STDERR, "| tee -ai errorlogs.txt");
MayurKubavat
  • 341
  • 4
  • 10