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

Hi, I am new to Perl. I want to append the following line to a text file whenever I find the word <body in the file: <link rel=\"stylesheet\" href=\"main/css/main.css\">\n Can someone suggest me how to write the code for this? I appreciate your help!
  • Comment on Append a line with special characters before a string

Replies are listed 'Best First'.
Re: Append a line with special characters before a string
by haukex (Archbishop) on Oct 03, 2017 at 08:01 UTC

    That doesn't sound like a text file to me, but like an HTML file. HTML is not a line-oriented format. What if the <body tag has attributes on the next line? What if the line that contains <body has tags immediately following it on the same line, or even the entire HTML file on one line, which is also possible? What I am trying to say is, use a proper parser. Also, why are you not inserting the <link> into <head>? Anyway, here's an example using Mojo::DOM:

    use warnings; use strict; use Mojo::DOM; my $html = q{<html><head><link id="1"/></head><body></body></html>}; my $insert = q{<link id="0"/>}; my $dom = Mojo::DOM->new($html); $dom->find('head')->each(sub { $_->child_nodes->first->prepend($insert) }); print "$dom\n"; __END__ <html><head><link id="0"><link id="1"></head><body></body></html>
Re: Append a line with special characters before a string
by Corion (Patriarch) on Oct 03, 2017 at 06:20 UTC

    The general approach would be to read the file line by line and append the <link ...> tag whenever you find <body ... in it.

    To give you more concise help, can you tell us where exactly you are having problems? If you show us the code you've already written, that helps us help you much better.

    Do you have problems with the general program structure? Are loops and conditional statements a problem for you?

    Do you have problems finding the <body string? Do you have example input data that you think should work with the code you have but doesn't?