w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
File not getting copied in perl

File "/root/actual" is not getting over written with content of "/root/temp" via perl script. If manually edited "/root/actual" is getting modified.

Do you mean that /root/temp isn't being replaced by /root/actual? Or is /root/temp being modified as you wish, but it's not copying over /root/acutual at the end of your program?

I suggest that you read up on modern Perl programming practices. You need to have use warnings; and use strict; in your program. In fact, many people on this forum won't bother answering Perl questions unless use strict; and use warnings; are used.

Where is $aref1[0] coming from? I don't see @aref1 declared anywhere in your program. Or, for that matter $profile_name.

If you're reading in the entire file into a regular expression, there's no reason to copy it over to a temporary file first.

I rewrote what you had in a more modern syntax:

use strict;
use warnings;
use autodie;

use constant {
    FILE_NAME => 'test.txt',

my $profile_name = "bar";                #Taking a guess
my @aref1 = qw(foo ??? ??? ???);         #Taking a guess

open my $input_fh, "<", FILE_NAME;
my @lines = <$input_fh>;
close $input_fh;

for my $line ( @lines ) {
    $line =~ s/$aref1[0]/$profile_name/;

open my $output_fh, ">", FILE_NAME;
print ${output_fh} @lines;
close $output_fh;

This works.


  1. use autodie; means you don't have to check whether files opened.
  2. When I use a for loop, I can do inplace replacing in an array. Each item is a pointer to that entry in the array.
  3. No need for copy or a temporary file since you're replacing the original file anyway.
  4. I didn't use it here since you didn't, but map { s/$aref1[0]/$profile_name/ } @lines; can replace that for loop. See map.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.