Write to a file in Perl

Home > Search
  by

or die $!

When attempting to open a file in Perl, it's always a good idea to use "or die" and $!. "or die" will display the text following the "or die" statement if the file cannot be opened, and $! will display the reason why the file could not be opened.

open(FH, ">", $file) or die "cannot open $file $! \n";

 


Overwrite (>)

When a single > is used, the file will be overwritten. In this example, the file is overwritten to contain "Line 1 Line 2 Line 3".

my $file = "/path/to/file.txt";
open(FH, ">", $file) or die "cannot open $file $! \n";
print FH "Line 1\n";
print FH "Line 2\n";
print FH "Line 3\n";
close FH;

 

Append (>>)

When two >> characters are used, text will be appended to the end of the file. In this example, "Hello World" is appended to the end of the file.

my $file = "/path/to/file.txt";
open(FH, ">>", $file) or die "cannot open $file $! \n";
print FH "Hello World\n";
close FH;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments