http://www.perlmonks.org?node_id=265989


in reply to Why XSLT and not just Perl?

Many good points have been raised about why XSLT exists, I won’t rehash them. I’d like to focus on this specific statement:

It just seems crippled compared to more robust languages (if XSLT can be considered a true language since there are no for or while functions, only for-each).

XSLT is not meant as a procedural language. Lisp, Scheme, Haskell, Prolog; are these not programming languages because they don’t include procedural loop constructs? When you create an XSLT document (script? program?) you don’t worry about the how of it, you just say what you want done. XSLT is a declarative language, and it's power lies in that.

A great example of the difference is an answer to a question asked today. Granted it’s a trivial example but it illustrates a larger point*.

# Copied from node 265898 by valdez. Cut and modified slightly. use HTML::TokeParser::Simple; use HTML::Entities; my $parser = HTML::TokeParser::Simple->new( 'filename' ); my $in_body = 0; while ( my $token = $parser->get_token ) { if ($in_body) { # we are inside BODY if ($token->is_text) { # it's text, convert it print HTML::Entities::encode_entities($token->as_is); } else { if ($token->is_end_tag( 'body' )) { # we've found the end of the BODY $in_body = 0; } print $token->as_is; } } else { if ($token->is_start_tag( 'body' )) { # we've found the beginning of the BODY $in_body = 1; } print $token->as_is; } }

Notice all the how bits; variables controlling when to loop and when to stop looping, the loop contructs themselves, conditionals to see if we’re in the tag or out of it, etc. Notice also that the program resembles the layout of the HTML document. What happens if the elements we want are three deep? Four? What about multiple distinct operations? Specification changes?

Now let’s look at an XSLT example of the same procedure (we’ll just imagine the encode_enties function exists):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Tr +ansform"> <xsl:template match="body//text()"> <xsl:value-of select="encode_entities(.)"/> </xsl:template> </xsl:stylesheet>

None of the how is needed in XSLT. You simply state what section of the document you’re interesetd in with XPath, what to do there, then apply the directive. Gone is the overhead (pre-amble, variables, loops, etc), the ties to the document structure, and problems with adding new rules. The how has been removed.

I'm not saying XSLT is the be-all or end-all, but it fits it's problem space well. Not being procedural can be a strength, you just have to learn to use it.


* Please note I'm not in any way insulting the answer, ‘trivial’ refers to the scope of my example.

Note: This obviously isn’t the only way to do XML transforms in Perl. However, it does illustrate (I hope) some of the differences between general and task based languages, as well as procedural vs. functional/declarative approaches.