vroom has asked for the wisdom of the Perl Monks concerning the following question: (files)

How do I write to a file?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I write to a file?
by revdiablo (Prior) on Jun 23, 2003 at 00:19 UTC

    The 3-arg form of open is fairly useful to prevent problems with filenames "tricking" perl, and other nasty surprises:

    open FH, ">", $outfile or die "Error writing '$outfile': $!\n"; print FH $output; close FH;

    Also useful are lexical filehandles:

    open my $filehandle, ">", $outfile or die "Error writing '$outfile': $ +!\n"; print $filehandle $output; close $filehandle;
Re: How do I write to a file?
by devslashneil (Friar) on Jun 22, 2003 at 04:41 UTC
    The Tie::File module can be used to bind an array to a file.

    Any changes you make to the array are then made retrospectivly to the file, without having to load the file into memory.

    This is especially useful for large files
    #!/usr/bin/perl use strict; use Tie::File; my @array; my $filename = 'foo.dat'; tie @array, 'Tie::File', $filename or die "Error: Cannot open $filenam +e\n"; push @array, "Hello, World!\n";
Re: How do I write to a file?
by DigitalKitty (Parson) on Apr 07, 2002 at 22:11 UTC
    A good idea when writing to a file is to include a space between the filename and the direction symbol. Like this:

    open(FH, "> sample.txt") or die("Cannot write to file: $!\n");

    Perl will ignore the extra space between the '>' and the filename. It is useful in preventing unexpected results.
Re: How do I write to a file?
by Crulx (Monk) on Jan 21, 2000 at 04:54 UTC
    The open command opens a file. The first few characters of the second argument tell you how the file is opened. This code
    open FH , ">$output_file";
    truncates and opens a file for writing. All the contents are lost.
    open FH, ">>$output_file";
    Opens a file for appending. When you start writing to this file, it will write to the end. To actually WRITE to that file you use the print command
    print FH "I will print this to a file\n";
Re: How do I write to a file?
by chromatic (Archbishop) on Mar 05, 2000 at 07:49 UTC
    Always, ALWAYS check the return value of a command such as open: open INPUT "myfile.txt" || die "Cannot open file: $!"; This will save you hours of aggregate troubleshooting when your program fails silently. (The special variable $! contains the error message. Print it to discover why the file couldn't be opened.)
      #I think you meant either open INPUT, "myfile.txt" or die "Cannot open file: $!"; #or (open INPUT, "myfile.txt") || die "Cannot open file: $!"; #"myfile.txt" || die "Cannot open file: $!" is always true