Write to a file in Perl

Daanish picture Daanish · Oct 5, 2012 · Viewed 77.4k times · Source

Consider:

#!/usr/local/bin/perl
$files = "C:\\Users\\A\\workspace\\CCoverage\\backup.txt";
unlink ($files);
open (OUTFILE, '>>$files');
print OUTFILE "Something\n";
close (OUTFILE);

The above is a simple subroutine I wrote in Perl, but it doesn't seem to work. How can I make it work?

Answer

Matteo picture Matteo · Oct 5, 2012

Variables are interpolated only in strings using double quotes ". If you use single quotes ' the $ will be interpreted as a dollar.

Try with ">>$files" instead of '>>$files'

Always use

use strict;
use warnings;

It will help to get some more warnings.

In any case also declare variables

my $files = "...";

You should also check the return value of open:

open OUTFILE, ">>$files"
  or die "Error opening $files: $!";

Edit: As suggested in the comments, a version with the three arguments open and a couple of other possible improvements

#!/usr/bin/perl

use strict;
use warnings;

# warn user (from perspective of caller)
use Carp;

# use nice English (or awk) names for ugly punctuation variables
use English qw(-no_match_vars);

# declare variables
my $files = 'example.txt';

# check if the file exists
if (-f $files) {
    unlink $files
        or croak "Cannot delete $files: $!";
}

# use a variable for the file handle
my $OUTFILE;

# use the three arguments version of open
# and check for errors
open $OUTFILE, '>>', $files
    or croak "Cannot open $files: $OS_ERROR";

# you can check for errors (e.g., if after opening the disk gets full)
print { $OUTFILE } "Something\n"
    or croak "Cannot write to $files: $OS_ERROR";

# check for errors
close $OUTFILE
    or croak "Cannot close $files: $OS_ERROR";