http://qs321.pair.com?node_id=11114080

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

Hello, this is my first attempt at parsing an HTML file. What I am trying to do is to substitute a string in the textual part of the HTML file. I can do this quite easily with the following code. What I am missing is probably the most easiest part: I do not want to extract and substitute the textual part (like now). What I want is to substitute my string and print out the original HTML (with changed part, of course). How should I proceed? (In my real-life example, I will need to match my string over two $sentence, but I leave this level of complexity for a later stage).

use strict; use warnings; use HTML::TreeBuilder; my $str = "<ul>" . "<div class=\"txt\" style=\"position:absolute; left:84px; top:73p +x;\"><span id=\"f1\" style=\"font-size:11px;vertical-align:baseline;c +olor:rgba(0,0,0,1);\">technology of S2S translation, also known as Sp +oken Language Translation (SLT),</span></div>" . "<div class=\"txt\" style=\"position:absolute; left:44px; top:73p +x;\"><span id=\"f1\" style=\"font-size:11px;vertical-align:baseline;c +olor:rgba(0,0,0,1);\">is a new application of AI,</span></div>" . "<li>there</li>" . "<li>everyone</li>" . "</ul>" ; # Now create a new tree to parse the HTML from String $str my $tr = HTML::TreeBuilder->new_from_content($str); # And now find all <li> tags and create an array with the values. my @lists = map { $_->content_list } $tr->find_by_tag_name('span'); # And loop through the array returning our values. foreach my $sentence (@lists) { $sentence =~ s/Spoken/SUBSTITUTION/; print $sentence, "\n"; }