How do I replace hash values ​​in an external file?

In my program, I am trying to replace the value of a specific hash in an external file with a new value. The external file is tab-limit from the key and I read the hash from the external file. I have been looking online and this is the closest way to know how to do this, but it doesn't seem to work.

            open(IN, ">>$file") || die "can't read file $file";
            while (<IN>) {
            print IN s/$hash{$key}/$newvalue/;
            }
           close (IN) 

      

I'm not entirely sure what I am missing in this formula.

+1


source to share


4 answers


Tie :: File can fix this for you.



use Tie::File;

tie @array, 'Tie::File', $file or die "Could not tie $file: $!";

for (@array) {
    s/$hash{$key}/$newvalue/;
}
untie @array;

      

+4


source


http://www.sthomas.net/roberts-perl-tutorial.htm/ch13/Modifying_a_File_with___I
google on "$ INPLACE_EDIT perl"



+1


source


You are trying to read and write to the same file, which won't work. You have to read, replace, and then write to another file. Subsequently, you can replace the input file with the one you just wrote if you really want one file.

0


source


It will be inefficient, but it should work if my perl-fu doesn't work:

open(IN, "<<$file") || die "can't read file $file";
open(OUT, ">>${file}.tmp") || die "can't open file $file";
while (<IN>) {
    print OUT s/$hash{$key}/$newvalue/;
}
close(IN);
close(OUT);
exec("mv ${file}.tmp $file");

      

Maybe a team to make the transition for you to perl, but I'm not a perl person.

0


source







All Articles