Writing to files

Basically, the FP below is the file pointer. You open a file using one (>) right angle bracket to overwrite the file with the contents, and two (>>) right angle brackets to append the contents to the file.

The variable $content contains the content you want to add to the file.

You can have as many print commands as you want, as long as they are in between open and close.

open(FP,">filename.txt");
print FP $content;
close(FP);

A better way to write to files

open my $fp, '>', 'filename.txt';
print $fp $content;
close $fp;

Another example

my $content = "write this content to file";
my $filename = 'filename.txt';
open my $fp, '>', $filename or croak "cannot open $filename: $OS_ERROR";
print $fp $content or croak "cannot write to $filename: $OS_ERROR";
close $fp or croak "cannot close $filename: $OS_ERROR";

Note: In order to use $OS_ERROR you need to use the module English.pm

Note: In order to use the croak function you must use the Carp.pm module.

Page Comments (Click to edit)

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Powered by pmwiki-2.2.0-beta65