Bootstrap FreeKB - Perl (Scripting) - Open file for writing appending overwriting (> and >>)
Perl (Scripting) - Open file for writing appending overwriting (> and >>)

Updated:   |  Perl (Scripting) articles

open is used to try to open a file for reading or writing. 

  • open < is used to open a file for reading
  • open > is used to open a file for writing, and the file will be overwritten
  • open >> is used to open a file for writing, to append new lines to the file

In this example, the file is overwritten to contain "Line 1 Line 2 Line 3".

my $file    = "/path/to/file.txt";
my $dirname = File::Basename::dirname($file);

if (not -e $dirname) { `mkdir --parents $dirname`; )

if (open FH, ">", $file and -w $file) {
  print FH "Line 1\n";
  print FH "Line 2\n";
  print FH "Line 3\n";
  close FH;
}
else {
  print "failed to open $file due to the following: $! \n";
  exit 1;
}

 

In this example, "Hello World" is appended to the end of the file.

my $file = "/path/to/file.txt";
my $dirname = File::Basename::dirname($file);

if (not -e $dirname) { `mkdir --parents $dirname`; )

if (open FH, ">>", $file and -w $file) {
  print FH "Hello World\n";
  close FH;
}
else {
  print "failed to open $file due to the following: $! \n";
  exit 1;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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