Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: Regex and writing lines in file

by amma (Novice)
on May 01, 2013 at 09:59 UTC ( #1031538=note: print w/ replies, xml ) Need Help??


in reply to Re: Regex and writing lines in file
in thread Regex and writing lines in file

I opened the file in string context and was able to find the pattern successfully. But I could not substitute the matched pattern with required pattern

$extra = "This is i will place after match\n.an this too"; open (my $fh, '+<', $file); $data = <$fh>; $data = s/(.*entry)\n([^\n]*)\n/$1\n$extra/

The $1 is found successfully. But could not do the substitution in the file.


Comment on Re^2: Regex and writing lines in file
Download Code
Re^3: Regex and writing lines in file
by Random_Walk (Parson) on May 01, 2013 at 11:38 UTC

    You have now substituted within the $data variable. Next you need to write the contents of $data back to the file. Try adding something like this after the substitution

    # untested seek $fh, 0, 0; # rewind to the start of the file print $fh $data; # Write the entire file close $fh;

    Of course this may not be very efficient if you have a large file to alter, but then inserting into the middle of a very big file never is. If you are frequently updating random records in a file you may need to start thinking about using a database.

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!

      Partially worked for me. Thank you!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1031538]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (16)
As of 2015-07-06 19:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (81 votes), past polls