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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Appending lines of text

 



klowery
Novice

May 20, 2014, 7:41 PM

Post #1 of 5 (3218 views)
Appending lines of text Can't Post

Is there a way to append subgroups of text onto a group?


Code
- Group1 
-- Subgroup1
-- Subgroup2
- Group2
-- Subgroup3
-- Subgroup4


To the following?


Code
Group1.Subgroup1 
Group1.Subgroup2
Group2.Subgroup3
Group2.Subgroup4



Laurent_R
Veteran / Moderator

May 20, 2014, 11:15 PM

Post #2 of 5 (3126 views)
Re: [klowery] Appending lines of text [In reply to] Can't Post

Yes, this is quite easy, except that you need to open your input file and to open a different output file (i.e. don't try to rewrite within the same file you are reading from). If you want to retain the original name, then you have to do some file renaming either before or after the main process. (There are some alternatives, such as loading the input into memory first and then writing, but this is the easiest to get started.)

Please let us know if you need help for processing the data lines, but if you have such difficulty the best would be that you show what you have tried and tell why it does not do what you want.


klowery
Novice

May 21, 2014, 7:17 AM

Post #3 of 5 (2953 views)
Re: [Laurent_R] Appending lines of text [In reply to] Can't Post

Ok I sort of understand what you are saying, but this does seem sort of difficult to do. Do I need to use regular expression to process the data lines?


BillKSmith
Veteran

May 22, 2014, 3:50 AM

Post #4 of 5 (2919 views)
Re: [klowery] Appending lines of text [In reply to] Can't Post

It is easier to process the data lines if you think of the problem as one of printing the subgroup lines with the group name prepended.


For each line of the file:

Read the line.

Separate the level info from the text using either split or a regular expression.

If it is a group level line, save the text as the group name.

Else prepend the previously saved group name to the text and print.
Good Luck,
Bill


Laurent_R
Veteran / Moderator

May 22, 2014, 10:19 AM

Post #5 of 5 (2802 views)
Re: [klowery] Appending lines of text [In reply to] Can't Post

Try this (untested - it assumes that you have already open the input file with the $IN file handler):


Code
my $group; 
while (my $line = <$IN>) {
chomp $line;
my ($level, $rest) = split /\s+/, $line;
if ($level eq "-") {
$group = $rest;
} else {
print $group, ".", $rest, "\n";
}
}


 
 


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

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