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

Updated:   |  Perl (Scripting) articles

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

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 or $file is NOT writable \n";
  exit 1;
}

 

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

if (open FH, ">>", $file and -w $file) {
  print FH "Hello World\n";
  close FH;
}
else {
  print "failed to open $file or $file is NOT writable \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 5722c4 in the box below so that we can be sure you are a human.