Write to a file in Perl

Home > Search

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";


Writing text to a file

The following markup is used to redirect the text Hello World to file.txt. A single > is used, meaning that the entire file will be overwritten with the text Hello World.

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


In this example, text is written to a CSV file. Use \n where you want your data to appear on the next line, and separate data with a comma.

my $file = "/path/to/file.csv";
open(FH, '>', $file) or die "cannot open $file $! \n";
print FH "Column1,Column2,Column3,Column4\n";
print FH "Data,Data,Data,Data\n";
print FH "Data,Data,Data,Data\n";


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.