1. Perl
  2. File I/O

Redirect standard output and write to a file

There is the easiest and most frequently used method to output to a file. Use the OS function called redirection to change the output to the display performed by the print function to a file.

The following is an example that displays a string on the display.

use strict;
use warnings;

# Write to file
print "writed to file\n";

Save the above file as example20080726.pl and at the command prompt or shell

perl example20080726.pl > Output file name

Please enter. (The output to the display is changed to the output to the specified file.)

Code explanation

(1) What is standard output?

"Standard output" is the display. The print function prints to the display, which is the standard output by default. You can also explicitly specify STDOUT, which means standard output, as shown below.

print "writed to file\n";

# Same as below
print STDOUT "writed to file\n" +

(2) Switch standard output by redirecting

perl example20080726.pl > Output file name

You can switch the standard output to a file with the> symbol. This feature is called a redirect. What you should see on the display is written to the file.

If you output to the standard output with the print function, you can output to the display or to a file.

Related Informatrion