Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a file in Perl

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?

like image 305
Daanish Avatar asked Oct 05 '12 04:10

Daanish


People also ask

How do I open a file in Perl write mode?

sysopen(DATA, "file. txt", O_RDWR|O_TRUNC ); You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY - to open file in read only mode.

How do I add a line to a file in Perl?

To insert a line after one already in the file, use the -n switch. It's just like -p except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add. To delete lines, only print the ones that you want.

How do I redirect output to a file in Perl script?

The syntax for the command shell on Windows resembles Bourne shell's. open STDOUT, ">", "output. txt" or die "$0: open: $!"; open STDERR, ">&STDOUT" or die "$0: dup: $!"; to the beginning of your program's executable statements.


1 Answers

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";
like image 71
Matteo Avatar answered Oct 04 '22 22:10

Matteo