Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

How do I write to a file?

by vroom (Pope)
on Jan 08, 2000 at 08:44 UTC ( #1880=categorized question: print w/replies, xml ) Need Help??
Contributed by vroom on Jan 08, 2000 at 08:44 UTC
Q&A  > files

Answer: How do I write to a file?
contributed by revdiablo

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;
Answer: How do I write to a file?
contributed by devslashneil

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";
Answer: How do I write to a file?
contributed by Crulx

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";
Answer: How do I write to a file?
contributed by DigitalKitty

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.
Answer: How do I write to a file?
contributed by chromatic

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.)

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others about the Monastery: (4)
    As of 2021-02-28 16:40 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found