EmmAngellow
EmmAngellow

Reputation: 81

How to write to an existing file in Perl?

I want to open an existing file in my desktop and write to it, for some reason I can't do it in ubuntu. Maybe I don't write the path exactly?

Is it possible without modules and etc.

open(WF,'>','/home/user/Desktop/write1.txt';

$text = "I am writing to this file";
print WF $text;

close(WF);
print "Done!\n";

Upvotes: 2

Views: 10607

Answers (2)

Polar Bear
Polar Bear

Reputation: 6818

Please see following code sample, it demonstrates some aspects of correct usage of open, environment variables and reports an error if a file can not be open for writing.

Note: Run a search in Google for Perl bookshelf

#!/bin/env perl
#
# vim: ai ts=4 sw=4
#

use strict;
use warnings;
use feature 'say';

my $fname = $ENV{HOME} . '/Desktop/write1.txt';
my $text  = 'I am writing to this file';

open my $fh, '>', $fname
    or die "Can't open $fname";

say $fh $text;

close $fh;

say 'Done!';

Documentation quote

About modes When calling open with three or more arguments, the second argument -- labeled MODE here -- defines the open mode. MODE is usually a literal string comprising special characters that define the intended I/O role of the filehandle being created: whether it's read-only, or read-and-write, and so on.

If MODE is <, the file is opened for input (read-only). If MODE is >, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is >>, the file is opened for appending, again being created if necessary.

You can put a + in front of the > or < to indicate that you want both read and write access to the file; thus +< is almost always preferred for read/write updates--the +> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the -i switch in perlrun for a better approach. The file is created with permissions of 0666 modified by the process's umask value.

These various prefixes correspond to the fopen(3) modes of r, r+, w, w+, a, and a+.

Documentation: open, close,

Upvotes: 0

vkk05
vkk05

Reputation: 3222

You have to open a file in append (>>) mode in order to write to same file. (Use a modern way to read a file, using a lexical filehandle:)

Here is the code snippet (tested in Ubuntu 20.04.1 with Perl v5.30.0):

#!/usr/bin/perl
use strict;
use warnings;

my $filename = '/home/vkk/Scripts/outfile.txt';
open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
print $fh "Write this line to file\n";
close $fh;
print "done\n";

For more info, refer these links - open or appending-to-files by Gabor.

Upvotes: 8

Related Questions