Perl Programming Page 5 - XSL Transformation with Perl |
Before I conclude this article, let me show you a final example. It incorporates some basic error handling that ensures that the end-user is not confronted with a screen of cryptic error messages. Incidently, Perl is notoriously famous for generating such messages.
Let’s assume that the "portfolio.xsl" style sheet file has been deleted by an ignorant colleague. Without any error handling, the above Perl script should spit out the following error message:
Definitely, a sight for sore eyes -- not only is it cryptic and complicated, bu I’ll frankly admit that even I was at a loss to understand the reasons behind the error. However, sanity prevailed after I added bits of the "error-handling", as seen in the listing above. Execute the Perl script in order to view the following output; I’ll continue to assume that the "portfolio.xsl" file has been deleted:
Alternatively, the script will spit out the following error message if the XML document was not found at its specified location:
To be frank, there’s no rocket science behind this, just some deft manipulation using the "eval" function, as seen below.
For the uninitiated, this "eval" function allows you to execute any Perl expression, and the results of the expression are stored in the special Perl "$@"variable. A quick check on the state of this variable helps you to determine if an error has occurred; if it is null, then all is well. However, if something goes wrong, Perl will store the error message in this variable, thereby allowing you to dictate the next course of action. Conclusion This brings us to end of the first part of XSL Transformations with Perl. Today, I showed you how to get started with the "XML::XSLT" package that allows you to transform XML documents using XSLT style sheets using Perl. After a simple example demonstrating the serve() method of the XML::XSLT() object, I demonstrated the transform() method, which returns an XML::DOM() object. Finally, I showed you how to add some basic error handling to your scripts in order to ensure better error handling in your Perl scripts. In the next part, I shall show you how to play around with the XML::DOM() and XML::XSLT() objects in the same Perl script as well as demonstrate some fancy XSL Transformations that’ll keep you coming back for more. Till then, happy transform()ing! Note: All examples in this article have been tested on Linux/i586 with Perl 5.8.0. Examples are illustrative only, and are not meant for a production environment. YMMV!
blog comments powered by Disqus |