perlmeditation
haukex
<p><small><i><b>A followup: [id://11116478]</b></i></small></p>
<p>Your employer/interviewer/professor/teacher has given you a task with the following specification:</p>
<blockquote>
<p>Given an XHTML file, find all the <c><div></c> tags with the <c>class</c> attribute "<c>data</c>"<sup>1</sup> and extract their <c>id</c> attribute as well as their text content, or an empty string if they have no content. The text content is to be stripped of all non-word characters (<c>\W</c>) and tags, text from nested tags is to be included in the output. There may be other <c>div</c>s, other tags, and other attributes present anywhere, but <c>div</c>s with the <c>class</c> <c>data</c> are guaranteed to have an <c>id</c> attribute and not be nested inside each other. The output of your script is to be a single comma-separated list of the form <c>id=text, id=text, ...</c>. You are to write your code first, and then you will be given a test file, guaranteed to be valid and standards-conforming, for which the expected output of your program is "<c>Zero=, One=Monday, Two=Tuesday, Three=Wednesday, Four=Thursday, Five=Friday, Six=Saturday, Seven=Sunday</c>"<sup>2</sup>.</p>
<p>
<small><i>Updates - Clarifications:</i></small><br>
<sup>1</sup> The <c>class</c> attribute should be exactly the string <c>data</c> (that is, ignoring the special treatment given to CSS classes). <small>Examples below updated accordingly.</small><br>
<sup>2</sup> Your solution should be generic enough to support any arbitrary strings for the <c>id</c> and text content, and be easily modifiable to change the expected <c>class</c> attribute.
</p>
</blockquote>
<p>Ok, you think, I know Perl is a powerful text processing language and regexes are great! And you write your code and it works well for the test cases you came up with. ... But did you think of everything? Here's the test file you end up getting:</p>
<spoiler>
<c>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"[
<!ATTLIST html
xmlns:xsi CDATA #FIXED "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation CDATA #IMPLIED > ]>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello, World</title>
<script type="text/javascript">
//<![CDATA[
console.log(' <div class="data" id="Hello">World</div> ');
//]]>
</script>
</head>
<body>
<div class="data" id="Zero" />
<div class="data" id="One">Monday</div><div class="data" id="Two">Tuesday</div>
<div id="Three" class='data'>Wednes<div id="day">day</div></div>
<div class="data" id='Four'><b>Thursday</b></div>
<div
class="data" id="Five">
Friday
</div>
<div
class
=
"data"
id
=
"Six"
>
<div
>
Satur
</div
>
day
</div
>
<div title=" class='data' id='Foo'>Bar"
id="Seven" class="data"> Sunday</div>
<div class="data otherclass" id="aaa">bbb</div>
<div class="otherclass" id="ccc">ddd</div>
<p class="data">eee</p>
<p id="fff">ggg</p>
<!--
<div class="data" id="Quz">Baz</div>
-->
<p><![CDATA[
<div class="data" id="Bye">Bye</div>
]]></p>
</body>
</html>
</c>
<p>Fun, right? While the above happens to be XHTML, the same problems (and more) of course apply to XML, and HTML also quickly gets much worse - just to name one example, did you know about [https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.7|SGML shorthand markup]? The following is perfectly valid HTML 4.01 (and even browsers may have trouble with it): <c><p<a href="/">foo</></c> <small>([https://www.w3.org/blog/2007/10/shorttags/|source])</small></p>
<p>If you're now thinking to yourself, "I've been working with this XML for a few years now and have never seen its format change", then imagine this scenario. The third party providing the XML hasn't touched their code, but decides to upgrade their OS libraries, including the one that writes the XML. Suddenly, you can no longer rely on the order of attributes, whitespace, etc., and your regex starts failing, and your bosses are on your back because they are losing money because their feeds are interrupted. Now take that thought a step further, and imagine you start working for a company where the person who wrote that regex is long gone, and you get to maintain it...</p>
<p>So I hope it is clear: Please, <b>don't try to parse arbitrary XML/HTML with regexes!</b> ([https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454|...just for fun]) Do yourself and the future maintainers of your code a favor and just use one of the many modules that are available.</p>
</spoiler>
<p>I encourage everyone to try and write a parser using your favorite module, be it:</p>
<ul>
<li>[mod://HTML::Parser] - Thank you, [fishy] and [tangent]!</li>
<li>[mod://HTML::TreeBuilder] / [mod://HTML::TreeBuilder::XPath] - Thank you, [tangent]!</li>
<li>[mod://Mojo::DOM] - see below</li>
<li>[mod://XML::LibXML] - Thank you, [Your Mother]!</li>
<li>[mod://XML::Twig] - Thank you, [Discipulus]!</li>
<li>[mod://XML::XSH2] - Thank you, [choroba]!</li>
<li>... your favorite here</li>
</ul>
<p>Honorable mentions: [Grimy] for a regex solution and [RonW] for a regex-based parser :-)</p>
<p>I'll kick things off with [mod://Mojo::DOM] (compacted somewhat, with potential for a lot more golfing or verboseness):</p>
<readmore>
<c>
use warnings;
use strict;
use Mojo::DOM;
my $dom = Mojo::DOM->new(
do { open my $fh, '<', 'example.xhtml' or die $!;
local $/; <$fh> } );
my $found = $dom->find('div[class="data"]')->map(sub {
( my $text = $_->all_text ) =~ s/\W//g;
{ id=>$_->attr('id'), text=>$text }
})->to_array;
my $out = join ', ', map { $_->{id}.'='.$_->{text} } @$found;
print $out,"\n";
$out eq "Zero=, One=Monday, Two=Tuesday, Three=Wednesday, "
."Four=Thursday, Five=Friday, Six=Saturday, Seven=Sunday"
? print "Good!\n" : die "BAD!\n";
</c>
<p><small><i><b>Updates after posting:</b> Minor updates to wording for clarification. Added test more cases to example file. <b>2017-10-17:</b> Replaced <c> </c> as discussed in the replies. Switched from XHTML 1.0 Transitional to XHTML 1.0 Strict. Added [https://www.w3.org/TR/xhtml1-schema/#together|Schema declaration]. Added output check to Mojo::DOM example. <b>2017-10-20:</b> A few minor updates to text.</i></small></p>
</readmore>
<p><b>Update 2017-10-18:</b> Thank you very much to everyone who has replied and posted their solutions so far, keep em coming! :-)</p>