Write to a file in 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?


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


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

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

Need Your Help

Draw polygons more efficiently with matplotlib

python numpy matplotlib scipy matplotlib-basemap

I have a dateset of around 60000 shapes (with lat/lon coordinates of each corner) which I want to draw on a map using matplotlib and basemap.

how to define a constant array in c/c++?

c++ c arrays const

How to define constant 1 or 2 dimensional array in C/C++?