FreeKB - Perl Write to a file (> and >>)
Perl - Write to a file (> and >>)

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) {
  print FH "Line 1\n";
  print FH "Line 2\n";
  print FH "Line 3\n";
  close FH;
}
else {
  print "failed to open $file \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) {
  print FH "Hello World\n";
  close FH;
}
else {
  print "failed to open $file \n";
  exit 1;
}

 



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 8da4f in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |