Hi,

I am trying to open a file and correct the spelling of friend. But when I open the file test.txt again it is all blank.

my $opened = open(MYFH , ">test.txt");

my $line;
my $lnum = 1;
while( $line = <MYFH> ){
  print "$lnum: $line\n";
 $line =~  s/freind/friend/g;
 print MYFH "$line";
  $lnum++;
}
close MYFH;

Dani AI

Generated

had the classic symptom: the edited file came back empty. correctly pointed toward the file-mode pitfall and offered the quick one-liner approach. For a robust, production-safe fix, prefer writing changes to a temporary file and atomically replacing the original once the write completes. That avoids truncation, half-written files, and gives an easy place for a backup.

A concise, safe pattern (uses core modules) is shown below. It streams the original, applies a substitution, writes to a temp file, then moves the temp over the original.

use strict;
use warnings;
use File::Temp qw(tempfile);
use File::Copy qw(move);

my $orig = 'test.txt';
open my $in, '<', $orig or die "open $orig: $!";
my ($out, $tmpname) = tempfile();
while (my $line = <$in>) {
    my ($bad, $good) = ('freind', 'friend');
    $line =~ s/\Q$bad\E/$good/g;
    print $out $line;
}
close $in;
close $out;
move $tmpname, $orig or die "replace failed: $!";

Notes and troubleshooting:

  • Use three-arg open and lexical filehandles; see the open documentation for details (open).
  • For atomic temp files and safe cleanup, see File::Temp. For moving/renaming, see File::Copy. move will attempt a rename (atomic on the same filesystem) or fall back to copy/unlink.
  • Watch encoding (use binmode or :encoding(...) if the file is UTF-8), use \b or \Q...\E to avoid accidental partial-word edits, and add /i for case-insensitive fixes if needed.
  • For very small files a slurp-and-replace is simpler; for large files the streaming/temp approach avoids high memory use.

This builds on and while giving a safe, practical workflow for in-place edits.

Recommended Answers

All 2 Replies

Hi techie929,

I *think* that you are getting an empty file because you are opening the file with ">", which will create a file if one does not exist, or *truncate* the file if it does exist. Therefore, the file is being truncated before you even get to read it into the rest of your script.

If you open it with "+<", you'll be able to read and write the existing file, but the problem with your *current* script is that you'll probably end up with each line being doubled.

You might want to think about *reading* from your input file, and *writing* the output to a second file (the perl -i "in-place" option might be a possibility as well...)

I hope this helps!

/usr/bin/perl -p -i -e "s/freind/friend/g" filename

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.