CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Text file manipulation with perl


New User

Oct 29, 2013, 1:50 AM

Post #1 of 4 (1679 views)
Text file manipulation with perl Can't Post

Hi Perl Gurus,

I am new to perl and having a bit of a hard time with manipulating a text file.

In this scenario I have two text files.

Text1.txt - which contains some text

Text2.txt - this is whats inside Text2.txt

<section 1></section1>   <section2></section2>

What I need the perl script to do is read Text2.txt and then locate <section1> and right after that insert the text from Text1.txt in between the <section1> and </section1> tags.

Can anybody help out with that? I know how to do it in other languages but am very lost in perl


Oct 29, 2013, 7:22 AM

Post #2 of 4 (1669 views)
Re: [huskysv] Text file manipulation with perl [In reply to] Can't Post

There are many ways to do this in Perl. The choice among them depends upon many factors which you did not tell us. How long are the files? Are the <section1> and </section1> tags always on the same line? Is Text2.txt an HTML document? Is it a template that never changes?

One approach that should always work is to slurp Text1 into a single string $string1. Slurp Text2 into $string2. Use a regular expression to replace the gap in $string1 with the contents of $string2. Use positive lookahead and positive lookbehind assertions to match the tags, but not include them in the matched text. (Refer to documentation on extended regular expressions)
Good Luck,

Veteran / Moderator

Oct 29, 2013, 10:52 AM

Post #3 of 4 (1664 views)
Re: [huskysv] Text file manipulation with perl [In reply to] Can't Post

I agree with Bill, we need more information, such as file size and the format of file1.Can you please provide a sample?


Oct 29, 2013, 3:47 PM

Post #4 of 4 (1654 views)
Re: [huskysv] Text file manipulation with perl [In reply to] Can't Post

Here is a complete perl program that does the substitution that I described in my last post. Note that the /x option allowed me to add whitespace and comments. The /m and /s options are not needed in this simple example. They do no harm in this case and they allow the substitution to work on a multiline string.

use strict; 
use warnings;
my $string1 = 'Insert this text in document';
my $string2 = 'stuff <section1></section1> more stuff <section2></section2>';

=~ s{
(?<= <section1> ) # Look behind
.* # Match anything between tags
(?= </section1> ) # Look ahead
{$string1}xms; # Replacement string

print $string2, "\n";

Good Luck,


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives