pawank86 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to open file and replace a line for string matching. my code looks like
open(my $FileH,"+<$meterFile"){ while (<$FileH>) { if ($_ =~ /sdpRowId:(.*)/){ #print "$_ \t $rowId\n"; $_ =~ s/sdpRowId:(.*)/sdpRowId: <ReplaceString>/g; print $FileH $_; } } close($FileH);
above code is appending the non-matching lines also in same file, i just want to search and replace same line.

Replies are listed 'Best First'.
Re: How to open file in Edit mode
by MidLifeXis (Monsignor) on Apr 30, 2014 at 13:15 UTC

    I would recommend using two files (yourcode.pl file.orig > file.new, for example).

    Unless you have fixed size records or $replace_string is smaller than what was matched, you are going to want to use two files or read the entire file into memory. If your replacement string is larger than your match, you will end up overwriting future portions of your file when you write the modified record back to your original file.

    As an example, if your replacement string is foobar, and your data file looks like:

    sdpRowId:blah sdpRowId:bar
    assuming that you have the file read/write code correct (it is not at this point in time), after the first pass, you would end up with something along the lines of:
    sdpRowId: foobar RowId:bar
    Note that the string 'sdp' at the beginning of the second line was overwritten.

    If you do insist on not using two files (or loading the entire data set into memory and rewriting the original file), you will probably need to find out about seek and tell.

    Update: Included an example

    --MidLifeXis

Re: How to open file in Edit mode
by Laurent_R (Canon) on Apr 30, 2014 at 21:53 UTC
    I would also recommend:

    - Loading the file into an array, modifying the array and writing the array back to the file, if the data is small enough to fit into an array;

    - Using two files, one for input and one for output, and doing the necessary housekeeping (deleting old file, renaming new one, whatever) afterwards.

    In theory, the tie function offers a possibility to edit in-place files. But I have yet to see a case where this solution would be superior to the two others above for this type of problem: for a small file, an array is much simpler and a bit faster; for a very large file, the two-file solution is slightly simpler and much much faster.

    Another possible solution in some cases is the -i flag of the command line. But that's really the two-file solution, except that Perl gives you some syntactic sugar in the way of doing the housekeeping for you.

Re: How to open file in Edit mode
by GotToBTru (Prior) on Apr 30, 2014 at 12:52 UTC

    We would need to see a sample of the data file.

    1 Peter 4:10