<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Scroll - Webquills.net</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/" />
    <link rel="self" type="application/atom+xml" href="http://www.webquills.net/scroll/atom.xml" />
    <id>tag:www.webquills.net,2008-06-29:/scroll//4</id>
    <updated>2008-09-25T14:38:27Z</updated>
    <subtitle>Better Perl for a Better Web</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type Pro 4.21-en</generator>

<entry>
    <title>Mason&apos;s caching improves performance, relieves database pressure </title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/09/masons-caching-improves-performance-relieves-database-pressure.html" />
    <id>tag:www.webquills.net,2008:/scroll//4.38</id>

    <published>2008-09-23T00:41:58Z</published>
    <updated>2008-09-25T14:38:27Z</updated>

    <summary>HTML::Mason is a template system with power tools built in. Here&apos;s a case study in the usefulness of Mason&apos;s internal caching tools. Mason reads from database As part of a web site registration application, the user is to be presented...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Templates" scheme="http://www.sixapart.com/ns/types#category" />
    
    <category term="mason" label="Mason" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p><a href="http://www.masonhq.com">HTML::Mason</a> is a template system with power tools built in. Here's a case study in the usefulness of Mason's internal caching tools.</p>

<h2>Mason reads from database</h2>

<p>As part of a web site registration application, the user is to be presented with a list of email newsletters the site makes available. During registration, the user may select one or more of the newsletters and be automatically subscribed. So I coded up a Mason component to display this list.</p>

<pre><code>&lt;%once&gt;
use ListDB;
&lt;/%once&gt;
&lt;%init&gt;
my @newsletters = ListDB::get_mailing_lists();
&lt;/%init&gt;
% for my $newsletter (@newsletters) {
    &lt;input id="subscribe" type="checkbox" name="subscribe" value="&lt;% $newsletter %&gt;"&gt;
    &lt;label for="subscribe"&gt;&lt;% $newsletter %&gt;&lt;/label&gt;&lt;br&gt;
%}
</code></pre>

<p>Of course this example is simplified, the real code has more HTML and a bit more display logic. It's not pretty, but it gets the job done. In the <code>once</code> section I import the library that interfaces with our mailing list database (which is managed by a separate application). Then we simply get a list of available newsletters and display each with an input checkbox. </p>

<h2>When database is busy, Apache gets tied up!</h2>

<p>As the website and the newsletters became more popular, we began to see problems. Specifically, when the mailing list software was performing some database intensive task, as it frequently did, the simple query underlying the call to <code>ListDB::get_mailing_lists()</code> would take a <em>very</em> long time to return. As a result, the user had to wait a minute or more for the page to load, and an Apache process was occupied waiting for the database to return.  If we ever had a time when the web site and the database were both busy at the same time, <em>all</em> our Apache processes could end up waiting for the database query, leaving none to serve pages. That's bad news for a web site!</p>

<p>The problem here, obviously, is that the code queries the database <em>every time</em> a user requests the registration form. This is not a problem that is unique to Mason, all dynamic web applications eventually run into it. Nor is the solution unique to Mason. But Mason makes the solution trivial to implement.</p>

<h2>Mason cache smoothes database bumps</h2>

<p>The solution, of course, is to cache the response from the database, so that the next web request does not need to hit the database in order to render the list. The list of newsletters doesn't change very often, so there is no harm in caching it. In fact, since the HTML rendering of the list won't change either, why not cache the HTML and save the rendering next time too?</p>

<p>If only Mason had a built-in cache system so I wouldn't have to go digging around for extra modules on CPAN and write another 20 lines of code. Oh wait, <em>it does</em>!</p>

<pre><code>&lt;%init&gt;
return if $m-&gt;cache_self(expire_in =&gt; 3600); # THE SOLUTION! (ALMOST)
require ListDB;
my @newsletters = ListDB::get_mailing_lists();
&lt;/%init&gt;
% for my $newsletter (@newsletters) {
    &lt;input id="subscribe" type="checkbox" name="subscribe" value="&lt;% $newsletter %&gt;"&gt;
    &lt;label for="subscribe"&gt;&lt;% $newsletter %&gt;&lt;/label&gt;&lt;br&gt;
%}
</code></pre>

<p>See, I told you Mason makes it easy! You can arrange for any component to cache its output with this simple incantation. If the component has previously been cached, <code>$m-&gt;cache_self</code> will return a true value, and the component will not execute again. Instead, the output will be fetched from the cache, without any further action on your part. Pretty neat, huh? But that's not all it does. If the component has <em>not</em> been previously cached, this routine will set a "hook" that will transparently cache the output of the current component execution once it has finished. Now that's just cool! I'll bet you can guess what the <code>expire_in</code> argument does. Yup, I'm telling it to cache the output for 3600 seconds (one hour), if the current cache happens to be empty.</p>

<p>Notice the other change I made. Instead of <code>use</code>ing our ListDB library in the <code>once</code> section, I have changed to a require statement. Why? Because in the general case, the library will not be needed for as much as an hour, because the content will be served from the cache. To save memory, we don't import the library until after the call the <code>$m-&gt;cache_self</code>, when we know we'll need it.</p>

<h2>After the cache expires, <em>le deluge</em></h2>

<p>Ah, but there's a flaw in your brilliant plan, I hear you say. What happens if the database happens to be slow <em>just</em> when the cache expires? You're right back where you started, with an empty cache and a whole bunch of Apache process waiting for data to fill it with.</p>

<p>Doggone it, why do you have to be so observant? I guess I'll have to break another tool out of Mason's bag of tricks. Watch <em>this</em>!</p>

<pre><code>&lt;%init&gt;
return if $m-&gt;cache_self(expire_in =&gt; 3600, busy_lock =&gt; 60); # THE SOLUTION!
require ListDB;
my @newsletters = ListDB::get_mailing_lists();
&lt;/%init&gt;
% for my $newsletter (@newsletters) {
    &lt;input id="subscribe" type="checkbox" name="subscribe" value="&lt;% $newsletter %&gt;"&gt;
    &lt;label for="subscribe"&gt;&lt;% $newsletter %&gt;&lt;/label&gt;&lt;br&gt;
%}
</code></pre>

<p>See what I did there? No? Look again at that first line of the <code>init</code> section. The new <code>busy_lock</code> argument is the key. Basically, that's telling the Mason cache, "Hey, if this object has expired, extend the life of the old cached value by 60 seconds so other processes will still get a cached value. Meanwhile, I'm gonna calculate a new value and cache that."</p>

<p>Now, when the cache "expires", only <em>one</em> Apache process will notice that fact. That one process will proceed to hit the database for the new value. Meanwhile, other processes will continue to find the old value in the cache for another 60 seconds. If the database does happen to be slow, only one user (per minute) will have a problem, and only one apache process will be hung waiting for data.</p>

<h2>HTML::Mason references</h2>

<ul>
<li>The <a href="http://www.masonhq.com">Mason home page</a></li>
<li>The <a href="http://www.masonhq.com/docs/manual/Devel.html#data_caching">Data Caching</a> section of the Mason developer guide</li>
<li>Get "The Mason Book", <a href="http://www.amazon.com/gp/product/0596002254?ie=UTF8&amp;tag=webquills-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596002254">Embedding Perl in HTML With Mason</a><img src="http://www.assoc-amazon.com/e/ir?t=webquills-20&amp;l=as2&amp;o=1&amp;a=0596002254" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
(also <a href="http://www.masonbook.com/">available online</a> )</li>
<li>Get <a href="http://search.cpan.org/dist/HTML-Mason/">Mason from CPAN</a></li>
</ul>
]]>
        

    </content>
</entry>

<entry>
    <title>Perl: Readability, Expressiveness, and Concision</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/07/perl-readability-expressivenes.html" />
    <id>tag:www.webquills.net,2008:/scroll//4.37</id>

    <published>2008-07-07T11:05:06Z</published>
    <updated>2008-07-07T11:48:34Z</updated>

    <summary>Writing readable code means expressing yourself as clearly and correctly as you can, not targeting the lowest common denominator of reader. There are many people out there who are preaching the gospel of readable code. I myself am one of...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<blockquote class="thesis">Writing readable code means expressing yourself as clearly and correctly as you can, not targeting the lowest common denominator of reader.</blockquote>

<p>There are <em>many</em> people out there who are <a href="http://use.perl.org/~Phred/journal/36799">preaching the gospel of readable code</a>. I myself am one of them. I am a strong proponent of expressive variable and subroutine names, for example. Unless you are a fire-and-forget contract programmer, you are going to be reading your code a lot more often than you write it. But honestly, if code readability is your primary concern, use Python, not Perl.</p>

<p>Reading good Python code is like reading a novel by Dan Brown or Michael Crichton. The language is clean and simple, allowing you to move forward easily, and quickly grasp the point of the story. The vocabulary is easily attainable and won't stretch your brain too far. I <em>like</em> reading Python code. It's an easy read &mdash; a beach read.</p>

<p>Reading good Perl code is like reading Shakespeare. Every line is deeply expressive, both in its content and its rhythm. You probably need a dictionary to look up some words that, while not perhaps in everyday usage, express <em>exactly</em> what the author intended. It's still English, but you have to work a little harder at reading it, because it's beautiful, powerful English. </p>

<p>When I write code, I <em>am</em> concerned about readability. But I am also concerned about <em>expressiveness</em> and <em>concision</em>. I have something I am trying to say. I don't always want two paragraphs of easy prose that approximate my point. Most of the time I want <em>le mot juste</em>, just the right word, a precise expression of exactly what I mean that requires no further elaboration. </p>

<p>Now, I don't intend to imply that my Perl is of a class with Shakespeare's verse (nor Flaubert's prose). What I am saying is that some stories cannot be told in terms of Dick and Jane and Spot. Complex problems often require complex language to describe their solutions. I love writing such solutions in Perl, because Perl, like English, offers me a broad and rich vocabulary of idiom I can use to construct complex works easily. </p>

<p>Those who speak pidgin-Perl can usually puzzle out what the code is doing, but they are going to get hung up at some points, and they are going to miss a lot of detail. That is not a flaw in the language, nor an error on the part of the writer. It is simply the nature of the form. But those who understand the depth of the language can truly appreciate the subtlety of a nice, tight hack. </p>

<p>The key to writing code that is both readable and expressive is to build a bridge with your comments that help the unfamiliar reader find his way through the complex and obscure portions. If you find yourself using a rare or arcane idiom because its the <em>right</em> thing to do, don't dumb it down into fifty lines of loops for novice programmers. Instead, write a full paragraph of explanation above your one-line hack. Include references to man pages, books, and web sites. Scholarly works always have footnotes. The reader will not only gain a better understanding of your code, but perhaps learn a new technique that improves his own.</p>

<p>Writing readable code does not mean writing for the lowest common denominator of reader. It means expressing your point as clearly and correctly as you can. Try to make your code readable, but don't sacrifice concision for readability. You should expect more from your reader, rather than expecting less from your code.</p>

<p>P.S. For another view on the subject, you can read about the <a href="http://humorix.org/articles/2000/09/unobfuscated/">Unobfuscated Perl Code Contest</a>.</p>

<p>P.P.S. For more deep(?) thoughts about Perl programming from <a href="http://www.webquills.net/scroll/">Webquills.net</a>, <a href="http://feeds.feedburner.com/Webquills">read the feed</a> or <a href="http://www.feedburner.com/fb/a/emailverifySubmit?feedId=929839&amp;loc=en_US">get new posts via email</a>. </p>
]]>
        

    </content>
</entry>

<entry>
    <title>The DBI Imp strikes!</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/06/the-dbi-imp-strikes.html" />
    <id>tag:www.webquills.net,2008:/scroll//4.35</id>

    <published>2008-06-26T17:17:04Z</published>
    <updated>2008-06-30T11:13:46Z</updated>

    <summary>Somewhere in the process of doing something or other in the last few weeks, I managed to break my installation of MySQL on my MacBook Pro. I can&apos;t remember now how I managed to break it, but I had shoved...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
    <category term="mysql" label="MySQL" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="osx" label="OSX" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="Perl" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Somewhere in the process of doing something or other in the last few weeks, I managed to break my installation of MySQL on my MacBook Pro. I can't remember now how I managed to break it, but I had shoved a note onto my "to do" list to fix it.</p>

<p>After downloading and installing the latest stable version of MySQL (5.0.51b), I discovered that Perl could no longer access the database. I figured I just needed to recompile DBD::mysql against the new MySQL libraries. But when I tried, I got complaints similar to this one:</p>

<blockquote>
  <p><code>Can't use dbi_imp_data of wrong size (127 not 124) at /System/Library/Perl/Extras/5.8.8/darwin-thread-multi-2level/DBI.pm line 1190.</code></p>
</blockquote>

<p>It seems I did two things wrong. First, I downloaded the "Mac OS X 10.5 (x86_64)" version of the MySQL server. Apparently, although Leopard (OSX 10.5) is supposed to be 64-bit, the included Perl 5.8.8 is compiled as 32-bit. So for compatibility, I scrapped MySQL and re-downloaded the 32-bit version. Of course, I may be mistaken about this, because...</p>

<p>I <em>still</em> got the errors! Some more searching suggested that some bug fixes in DBI for FreeBSD might be related. I was using the pre-installed DBI 1.52, and that was error number two. So I upgraded to the latest DBI (1.605), <code>make realclean</code>, and tried again.</p>

<p>I got a warning when running Makefile.PL:</p>

<blockquote>
  <p><code>Multiple copies of Driver.xst found in: /Library/Perl/5.8.8/darwin-thread-multi-2level/auto/DBI/ /System/Library/Perl/Extras/5.8.8/darwin-thread-multi-2level/auto/DBI/ /Library/Perl/5.8.6/darwin-thread-multi-2level/auto/DBI/ at Makefile.PL line 759</code></p>
</blockquote>

<p>It seems to be detecting both the original Apple version of this file, and the new one I just installed from CPAN. However, I was still able to build the software, so apparently this is a pickled herring or whatever you call those things that look scary but don't actually matter.</p>

<p>Whew! Now we're back up and running. I'm tempted to try the 64-bit version again to see if it will work now that I have updated DBI, but that's too much like work, and since I only need it for testing, it isn't very important.</p>

<p>The moral to the story? Erm ... Don't break stuff? I'm not sure, but anyway, if my experience helps you get your MySQL working faster, I'll be happy.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>ORM - PITA?</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/06/orm-pita.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.24</id>

    <published>2008-06-14T23:25:35Z</published>
    <updated>2008-06-14T23:32:05Z</updated>

    <summary>Recently I read a note called DBIx::Class Gotchas over at Perl Alchemy. I&apos;ve been struggling myself for several months with a bundle of old Class::DBI code, and I can relate. Both packages fall into the category of Object-Relational Mapping (ORM),...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    <category term="orm" label="ORM" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Recently I read a note called <a href="http://perlalchemy.blogspot.com/2008/06/dbixclass-gotchas.html">DBIx::Class Gotchas</a> over at <a href="http://perlalchemy.blogspot.com/">Perl Alchemy</a>. I've been struggling myself for several months with a bundle of old <a href="http://search.cpan.org/dist/Class-DBI/">Class::DBI</a> code, and I can relate. Both packages fall into the category of Object-Relational Mapping (ORM), software that tries to map programming objects around entities stored in a relational database.</p>

<p>For a long time I was a huge proponent of ORM software, and I still am for certain types of projects. But the honeymoon is over for me, as I've started to hit some of those limitations they always warn you about. ORM buys you a big gain in productivity, because the software reduces database access patterns from a dozen lines of code to just one or two. If you need to get a small project up and running fast, ORM is a tool that can help a great deal.</p>

<p>The trouble with ORM is that your objects don't always map directly to the queries you want to make. To simplify the thorny problem of SQL generation, often the underlying implementation is doing things in Perl code that would be more efficiently done in the database, or executing multiple SQL queries when a single join would have done the trick. When your project gets very large, very complex, or very dependent on database performance, the ORM layer suddenly seems to hinder as much as it helps. I now spend as much of my time coding <em>around</em> the ORM layer as using it.</p>

<p>Still, without ORM I would spend a lot more time writing "select * from table" queries and the like, and I almost always have the need to optimize for development time rather than execution time. So I have this love/hate relationship.</p>

<p>What's your experience with ORM software? Love it? Hate it? Tolerate it?</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Perl 5: Hash slices can replace loops</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/05/perl-5-hash-slices-can-replace.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.23</id>

    <published>2008-05-26T16:00:57Z</published>
    <updated>2008-05-26T16:07:37Z</updated>

    <summary>How many times have you written a for loop to do something simple with a hash and thought, there must be a better way to do this? Using hash slices instead of simple loops can save you lines of code...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Programming" scheme="http://www.sixapart.com/ns/types#category" />
    
    <category term="hash" label="hash," scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl," scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="slice" label="slice" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>How many times have you written a <code>for</code> loop to do something simple with a hash and thought, there must be a better way to do this? Using hash slices instead of simple loops can save you lines of code and execution time.</p>

<p>A <em>hash slice</em> is a syntax for accessing the values of multiple keys of a hash in a single statement. It is a succinct and efficient technique, but it is also one of those collections of punctuation that give Perl a reputation as a write-only language. Once you have learned it, however, you will feel much more clever! Here are a few examples of how I use hash slices to make my code shorter and faster. (Note that you can also slice arrays, but today we are just talking about hashes.)</p>

<h2>Basic hash slice syntax</h2>

<p>You perform a hash slice by using a list as a hash index, rather than a scalar value, and preceding with the <code>@</code> sigil rather than the <code>$</code> sigil you would use to get a scalar value.</p>

<pre><code>my %number_for = (one =&gt; 1, two =&gt; 2, three =&gt; 3);
# Regular access to scalar key
print $number_for{one}; # 1
# Hash slice accesses multiple keys. Note the '@'
print @number_for{qw(one two three)}; # 123
# This also works
print @number_for{'one','two','three'}; # 123
</code></pre>

<p>A cautionary note: notice how the scalar index uses a bare word as the key. Perl gives you the quoting for free in this case. With a slice, Perl doesn't help, so you have to do the quoting yourself.</p>

<h2>Merging two hashes</h2>

<p>Since hash slices can be lvalues, they can be used to merge one hash into another. A common example is when you get configuration information from more than one source, but you want to consolidate it to look up in just one place.</p>

<pre><code>my %your_numbers = (two =&gt; 2, four =&gt; 4, six =&gt; 6);
# I get all your numbers! 
# (And your number will override mine if they differ)
@number_for{keys %your_numbers} = values %your_numbers;
print sort values %number_for; # 12346
</code></pre>

<h2>Accessing keys in a particular order</h2>

<p>Here is a common thing you run into in web development. You have received input from a web form and validated it. (You <em>have</em> validated it, right?) The data lives in a hash, and you want to store it in a database. You have your SQL statement all prepared, but it requires that the values be bound in exact column order. Unfortunately, the <code>values</code> function cannot be relied upon to return the values in the order you want. (And besides, you don't want to store the value of the submit button!)</p>

<pre><code># get valid data from your validation code
my %validated = %number_for;
# Columns of your table, in order needed by your SQL
my @columns = qw(six one three);
# Get the bind values with a slice
my @bind = @validated{@columns}; # 6,1,3
</code></pre>

<h2>Accessing values sorted by keys</h2>

<p>Say you want to sort a hash by its keys, and then use the values in that sorted order. Using the above data, perhaps we want to print numbers in alphabetical order.</p>

<pre><code>print @number_for{sort keys %number_for}; # 41632
</code></pre>

<h2>Slicing a hash reference</h2>

<p>Eventually you will find yourself with a reference to a hash, and you will discover that the above syntax does not work. You may try three or four different combinations of curlies and arrows that just generate errors. Don't give up! You <em>can</em> slice a hashref! First, let's review using a hashref to get at scalar values.</p>

<pre><code>my $num_for = \%number_for;
# Common syntax for dereferencing and getting a scalar index
print $num_for-&gt;{one}; # 1
# Alternate syntax, the lazy way:
print $$num_for{two}; # 2
# Alternate syntax, the explicit way
print ${$num_for}{six}; # 6
</code></pre>

<p>The key to slicing a reference to a hash is to use the alternate syntax shown above, replacing the initial <code>$</code> sigil with <code>@</code>.</p>

<pre><code># The lazy way:
print @$num_for{@columns}; # 613
# The explicit way:
print @{$num_for}{@columns}; # 613
</code></pre>

<p>Note the distinct absence of the "arrow" syntax. The arrow implies a scalar, and we want a list.</p>

<h2>Powerful syntax</h2>

<p>The hash slice is an advanced syntax demonstrating Perl's concision and expressiveness. Now you should be able to recognize it when you see it, and hopefully apply it to your own projects to save time and space. (But remember, use your Perl superpowers only for Good, never for Evil!)</p>

<p>For a semi-regular diet of great Perl programming tips, <a href="http://feeds.feedburner.com/Webquills">subscribe to the Webquills.net feed</a> or <a href="http://www.feedburner.com/fb/a/emailverifySubmit?feedId=929839&amp;loc=en_US">get Webquills.net via email</a>. </p>
]]>
        

    </content>
</entry>

<entry>
    <title>Best Error Message Ever</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/03/best-error-message-ever.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.22</id>

    <published>2008-03-15T22:12:33Z</published>
    <updated>2008-03-15T22:16:24Z</updated>

    <summary>Oh, the irony is so heavy, it&apos;s breaking me!...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Oh, the irony is so heavy, it's breaking me!</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="Best Error Ever.png" src="http://www.webquills.net/scroll/Best%20Error%20Ever.png" width="523" height="224" class="mt-image-none" style="" /></span></p>
]]>
        

    </content>
</entry>

<entry>
    <title>Perl Tool Tip: module_info</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/02/perl-answering-questions-about.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.18</id>

    <published>2008-02-19T02:45:00Z</published>
    <updated>2008-02-19T02:53:59Z</updated>

    <summary>When developing and deploying Perl code that relies heavily on CPAN modules (and if yours doesn&apos;t, it&apos;s either really simple, or you are not using Perl to its full potential), I find myself asking the same set of questions over...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>When developing and deploying Perl code that relies heavily on CPAN modules (and if yours doesn't, it's either really simple, or you are not using Perl to its full potential), I find myself asking the same set of questions over and over again.</p>

<ul>
<li>Do I have ${ModuleX} installed on this machine?</li>
<li>What version of ${ModuleX} is installed?</li>
<li>There might be more than one copy of ${ModuleX}. Which one is my code using?</li>
<li>${ModuleX} is not behaving. I want to have a look at its source.</li>
</ul>

<p>A handy (and free) tool to help answer these questions is available from CPAN in the <a href="http://search.cpan.org/dist/Module-Info/">Module::Info</a> distribution. In addition to the library, this distribution also includes the <code>module_info</code> command line script. Run it to find out the version and location of the module in question. For example:</p>

<pre><code>vince@Vince-Laptop:~$ module_info Module::Info

Name:        Module::Info
Version:     0.310
Directory:   /Library/Perl/5.8.6
File:        /Library/Perl/5.8.6/Module/Info.pm
Core module: no
</code></pre>

<p>You can quickly find out what version of the module is installed, where it lives, and even whether it is a part of the Perl core distribution. Sadly, <code>Module::Info</code> itself is <em>not</em> in the Perl core, so you'll have to install it and its dependencies from CPAN.</p>

<p>If you can't install the CPAN module for some reason, I hacked together a little script I call <code>qmod</code> that I could carry around on a thumb drive with my dot-files and such. Being just a quick hack, it's not as functional as <code>module_info</code>, but it gets the job done. Here it is in its entirety (less documentation).</p>

<pre><code>#!/usr/bin/perl
use strict;
my $max = 0;
my @list;
for (@ARGV) {
    $max = length($_) &gt; $max ? length($_) : $max;
    eval  "require $_;" ;
    if ( $@ ) {
        push @list, [$_, 'Not Found', ''];
    } else {
        my ($version,$file,$which);
        ($file = "$_.pm") =~ s{::}{/}g; 
        my $varname = $_ . "::VERSION";
        eval "\$version = \$$varname;";
        push @list, [$_, $version, $INC{$file}];
    }#END if
}#END for
printf "%-${max}s  %6s  %s \n", @{$_} for @list;
</code></pre>

<p>If you just need to know the location of a module file, here's a nice tip from brian d foy's <a href="http://www.amazon.com/gp/product/0596527241?ie=UTF8&amp;tag=controlescape-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527241">Mastering Perl</a><img src="http://www.assoc-amazon.com/e/ir?t=controlescape-20&amp;l=as2&amp;o=1&amp;a=0596527241" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />: <code>perldoc -l Module::Info</code>.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Inside-out Templates in Perl</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/02/insideout-templates-in-perl.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.21</id>

    <published>2008-02-09T12:57:44Z</published>
    <updated>2008-02-29T03:30:21Z</updated>

    <summary>Pop quiz, hotshot. Your team has undertaken a project to completely redesign your web site. Fancy-pants designers are hard at work generating not one but three new designs. The designs will be put through a battery of usability tests, after...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Templates" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Pop quiz, hotshot. Your team has undertaken a project to completely redesign your web site. Fancy-pants designers are hard at work generating not one but <em>three</em> new designs. The designs will be put through a battery of usability tests, after which the best parts will be combined into the final design. They need <em>you</em> to create server-side logic that will populate content areas, navigation, and various design elements according to how the user manipulates the site. But the HTML is nowhere near finished, and the designers will be tweaking it right up to the day of the test. <em>What do you do?</em></p>

<p>Your normal workflow is shot. Typically you receive finished HTML from the designers, break it down into reusable components, add template tags to represent program objects and logic, and prepare the whole thing to be run through a template processor to generate output. That's out. Any attempt to mess with their HTML will be counter-productive. The priority here is to perfect the design for usability testing, and that means rapid iteration in visual design tools. Template tags will get in the way.</p>

<p>The time crunch is serious. They need a <em>functional</em> prototype to test with, but you can't embed the functionality into the template. They're holding your templates hostage.</p>

<p>My solution: Shoot the hostage.</p>
]]>
        <![CDATA[<h2>Binding logic to document structure</h2>

<p>The key to solving a seemingly impossible problem is not to come up with a seemingly impossible solution. It is to reframe the problem into something that's easier to solve.</p>

<p>In this situation, the problems <em>seems</em> to be that I have to embed my template logic into these HTML files at the last minute, with no hope of having time for testing. Since this is nearly impossible, let's break down the problem. What is the template logic going to actually do? </p>

<ol>
<li>Extract content from a database, keyed by the requested URL, and wrap it in one of the provided designs.</li>
<li>Rewrite the navigation section according to the URL of the current page.</li>
<li>Perform several variable substitutions based on the site being tested.</li>
</ol>

<p>None of these things are really dependent on the particular HTML design they are going into. They are just inserting or changing some content at a particular position in the document structure. I can write this logic without having the HTML. The trouble is, the logic does not do anything until it is bound to the document structure in some way. Template systems perform this binding by <em>embedding</em> the logic into the structure itself. Since I can't put template markers into the HTML, what I need is a way to bind the logic to the document structure <em>from the outside</em>.</p>

<p>Being a Perl hacker, my first thought was, can I rewrite the content using a regular expression string substitution? Having a look at the HTML in progress, I quickly decided this was an unreliable method. If they changed the order of tags or attributes, which they were sure to do, everything would break, and I would be up all night debugging regular expressions. Not my idea of a party.</p>

<p>If only this were a client-side application, I found myself thinking. Then I could use <a href="http://jquery.com/">jQuery</a> or another javascript toolkit to rewrite the <abbr title="Document Object Model">DOM</abbr> at the client. In old-school javascript, this wouldn't be much better, but modern techniques like <a href="http://domscripting.com/blog/display/41">Hijax</a> allow you to separate the code from the structure to manipulate the DOM from the outside.</p>

<p>Hang on a minute. At the server, I have access to everything the client has and then some. Can't I build a DOM at the server and manipulate it in Perl?</p>

<h2>An inside-out template using HTML::TreeBuilder</h2>

<p>Off to <a href="http://search.cpan.org">CPAN Search</a>, and in minutes I was writing my first experimental script with <a href="http://search.cpan.org/dist/HTML-Tree/">HTML::TreeBuilder</a>. I started with something like this:</p>

<pre><code>#!/usr/bin/perl
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder-&gt;new();
$tree-&gt;parse_file('wrapper.html');

my @links = $tree-&gt;look_down( _tag =&gt; 'a');

printf 'Found %s links', scalar(@links);
print "\n";
for (@links) {
        print $_-&gt;attr('href'),"\n";
}
</code></pre>

<p>Sure enough, I was able to print out all the linked URLs just like that! </p>

<p>My next step was not code, but social engineering. I talked to our designers and established that all the HTML designs would use the same HTML id attributes for the same document elements, and that these id attributes would not change. I needed this structural stability for my code to work. Fortunately, our clever designers were already on the ball and didn't have to change a thing.</p>

<p>I quickly implemented some procedural code that would perform the replacements I was after. Most of the code was spent loading the strings and structures that would serve as replacement text, so it isn't really useful to display here. But here are a few tips that might help you out if you decide to use HTML::TreeBuilder in your application.</p>

<h3>TreeBulder Tip 1: Comments are stripped by default</h3>

<p>The designers needed to see their "trace" comments in the output of the processed template. HTML::TreeBuilder throws comments away by default. To keep them:</p>

<pre><code>my $tree = HTML::TreeBuilder-&gt;new();
$tree-&gt;store_comments(1); # Before parsing!
</code></pre>

<p>This makes comments appear as separate nodes in the tree, with a tag of <code>~comment</code>. You can also preserve PHP code and other processing instructions using <code>$tree-&gt;store_pis(1)</code>, and preserve the DOCTYPE declaration with <code>$tree-&gt;store_declarations(1)</code>, although I didn't need to.</p>

<h3>TreeBuilder Tip 2: Enable parsing XML-style empty element tags</h3>

<p>My designers were using tools that produced (for the most part) valid XHTML. In XHTML, the empty tag syntax is used for tags like <code>link</code> and <code>img</code>.</p>

<pre><code>&lt;link rel="stylesheet" href="/global.css" /&gt;
            &lt;!-- XHTML Empty tag syntax  ^^^ --&gt;
</code></pre>

<p>TreeBuilder's default parse mode (inherited from HTML::Parser) treats these trailing slashes as character data. This didn't cause any actual problems for me, but better safe than sorry. I explicitly enabled support for empty tags this way:</p>

<pre><code>$tree-&gt;empty_element_tags(1); # Before parsing!
</code></pre>

<h3>TreeBuilder Tip 3: Be explicit with <code>as_HTML()</code></h3>

<p>To turn the in-memory model back into HTML text for output, you use the <code>as_HTML()</code> method. This method can be called with no arguments, in which case it implements some default behaviors which are almost certainly not what your designers want.</p>

<p>The first argument describes what character entities should be HTML encoded in PCDATA (i.e. text nodes). By default, it encodes everything that <a href="http://search.cpan.org/perldoc?HTML%3A%3AEntities">HTML::Entities</a> knows how to encode. This is probably overkill. The docs say that you can be compatible with previous versions by passing '&lt;>&amp;'.</p>

<p>The second argument is the "indent string". By default this is undefined, which is nice for production since it eliminates unnecessary white space in the output. But when you are debugging the output, it's nice to have it "pretty printed". So I specified a four-space indent. With this setting, TreeBuilder neatly aligns open and close tags, making debugging much easier.</p>

<p>The third and most important argument defines elements whose end-tags are "optional", and by optional it means <em>omitted</em>. If you want your HTML to validate, and more importantly not be <em>broken</em>, you need to pass an empty hash reference for this argument. Missing <code>&lt;/p&gt;</code> tags can seriously screw up a CSS based layout in certain circumstances, as I discovered the hard way.</p>

<p>So the <em>correct</em> way to call <code>as_HTML()</code> is like this:</p>

<pre><code>$w_tree-&gt;as_HTML('&lt;&gt;&amp;','    ',{});
</code></pre>

<h3>TreeBuilder Tip 4: Don't use <code>as_XML()</code> unless you <em>really</em> mean it</h3>

<p>If you are producing XHTML code, you might be tempted to call <code>as_XML()</code> instead of <code>as_HTML()</code> to serialize your tree. And you would be correct. But remember that XML is <em>very strict</em> about how things must be structured, and TreeBuilder complies with this strictness.</p>

<p>One of the sneaky things that will bite you is that in XHTML, script tags have a content model of PCDATA. This means that a <em>correct</em> XML generator must encode entities contained by the tag. And if this happens (as it will if you call <code>as_XML()</code>), your Javascript just got completely mangled and will no longer run. (Unless, of course, you used the magic incantation to wrap your script contents in CDATA sections.) You can read more about the issues on <a href="http://developer.mozilla.org/en/docs/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents">Moz Dev</a>. However, I found the safest route was to output HTML 4.01 instead. Using an HTML 4 DOCTYPE still triggers standards mode in web browsers, but doesn't have all the <a href="http://hixie.ch/advocacy/xhtml">pitfalls of serving XHTML</a>.</p>

<h3>TreeBuilder Tip 5: HTML::Element::Library</h3>

<p>I discovered this too late to use it myself, but <a href="http://search.cpan.org/perldoc?HTML::Element::Library">HTML::Element::Library</a> extends HTML::Element with some finger-saving shortcuts. Several times I ended up writing a code stanza that looked like this:</p>

<pre><code>my $e = $tree-&gt;look_down(id =&gt; 'replaceMe');
$e-&gt;delete_content();
$e-&gt;push_content($replacement);
</code></pre>

<p>With HTML::Element::Library, you can do this instead:</p>

<pre><code> $tree-&gt;look_down(id =&gt; 'replaceMe')-&gt;replace_content($replacement);
</code></pre>

<h2>TreeBuilder Pros and Cons</h2>

<p>I think TreeBuilder was the the right tool for the job I had to do. It allowed me to manipulate HTML documents at the server <em>without</em> embedding code-specific markers in the document itself. This allowed my team to generate both HTML and server-side Perl code in parallel, and we met our targets with room to spare.</p>

<p>That said, I don't think I would want to use TreeBuilder as my regular template tool. Binding logic to the HTML structure using procedural Perl takes a lot more code than just embedding it into the template. More code means more typing, more testing, and more bugs. <a href="http://search.cpan.org/perldoc?HTML::Seamstress">HTML::Seamstress</a> tries to help, and certainly should be considered if you are using more than one or two templates with this method, but Seamstress doesn't eliminate code so much as generate it for you. Better, but still not what I want.</p>

<p>What I <em>really</em> want is a concise, declarative syntax for binding logic to the document structure. No, not XSLT. I said "concise". I can definitely write Perl code faster than XSLT, and the resulting code is shorter and easier to read.</p>

<p>What would be nice is something very like a CSS stylesheet, but with code blocks instead of style attribute assignments inside the curly braces. Or maybe just a Perl port of jQuery. That would be <em>way</em> cool. Anybody want to build that for me? (UPDATE: see <a href="http://search.cpan.org/perldoc?pQuery">pQuery</a>)</p>

<h2>Pop culture note</h2>

<p>For those too young to remember, "Pop quiz, hotshot", "What do you do?", and "Shoot the hostage" are references to the 1994 action movie <a href="http://www.amazon.com/gp/product/B0006GANOQ?ie=UTF8%26tag%3Dcontrolescape-20%26linkCode%3Das2%26camp%3D1789%26creative%3D9325%26creativeASIN%3DB0006GANOQ">Speed</a><img src="http://www.assoc-amazon.com/e/ir?t=controlescape-20%26l%3Das2%26o%3D1%26a%3DB0006GANOQ" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, a classic of my generation.</p>
]]>
    </content>
</entry>

<entry>
    <title>HTML::Mason 1.39 - Now with Memcached</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/02/htmlmason-139-now-with-memcach.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.20</id>

    <published>2008-02-04T03:25:14Z</published>
    <updated>2008-02-04T03:43:05Z</updated>

    <summary>Speaking of templates, I was just catching up on my mailing list deluge, and found this announcement for the latest release of HTML::Mason: 1.39 Jan 30, 2008 [ ENHANCEMENTS ] CHI may now be used as the backend for $m-&gt;cache...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
    <category term="mason" label="Mason" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="memcached" label="Memcached" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Speaking of templates, I was just catching up on my mailing list deluge, and found this announcement for the latest release of <a href="http://masonhq.com">HTML::Mason</a>:</p>

<blockquote>
  <p>1.39  Jan 30, 2008</p>
  
  <p>[ ENHANCEMENTS ]</p>
  
  <p>CHI may now be used as the backend for $m->cache as an updated
  alternative to Cache::Cache.  Among other things, this facilitates
  easy use of Cache::FastMmap and memcached for data
  caching. Cache::Cache is still the default for now, and is still
  listed as a prereq for Mason.</p>
  
  <p>-dave</p>
</blockquote>

<p>Memcached support puts a smile on my face! I need to test that out <em>soon</em>! <a href="http://masonhq.com/docs/manual/Devel.html#choosing_a_cache_subclass__with_">Read the docs</a>.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Choose the right template system for your team</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2008/01/choose-the-right-template-syst.html" />
    <id>tag:www.webquills.net,2008:/scroll//1.19</id>

    <published>2008-01-30T03:53:18Z</published>
    <updated>2008-02-19T02:56:28Z</updated>

    <summary>What is the best template system? Ask five people and you&apos;ll probably get six different answers. Perl has more than its fair share of template tools, from the Swiss Army Chainsaw of Template Toolkit, through HTML::Mason and Text::Template down to...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Templates" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>What is the best template system? Ask five people and you'll probably get six different answers. Perl has more than its fair share of template tools, from the Swiss Army Chainsaw of <a href="http://search.cpan.org/dist/Template-Toolkit/">Template Toolkit</a>, through <a href="http://search.cpan.org/dist/HTML-Mason/">HTML::Mason</a> and <a href="http://search.cpan.org/dist/Text-Template/">Text::Template</a> down to the ever-tempting "variables interpolated in a here-doc" method.</p>

<p>As always with this type of question, there is no "correct" answer. The best template system is the one that works best for you, in your circumstances. If you are the only programmer in a room full of professional designers, your optimal template choice is likely to be different than if you are just trying to stick a loop into a text file for your own cron job. </p>

<p>In my experience, the key factors in choosing a template system are usually the composition of your development team, and the development workflow. Who has to work with the templates, and what are their skill sets? Is the code being designed around the interface, or is the interface being pasted on top of the code?</p>

<p>Read on for a comparison of the major template systems in Perl, and my recommendations of which systems fit which circumstances.</p>
]]>
        <![CDATA[<h2>Solo Perl Hacker: Text::Template</h2>

<p>If you are a Perl programmer and you are producing your own templates, whether they be an HTML front-end or a plain text email, you can hardly go wrong by starting with <a href="http://search.cpan.org/dist/Text-Template/">Text::Template</a>. This is the shortest path from Perl code to output, short of variable interpolation in a double-quoted string. The syntax is just plain old Perl, and everything you know about Perl translates directly to effective templates.</p>

<p>The down-side, of course, is that you do not enforce a clear separation of concerns. As a programmer intimately familiar with the internals of your application, you will be tempted to embed all sorts of application logic into the templates themselves. This makes your application harder to test and harder to maintain.</p>

<p>There is nothing in Text::Template that forces you to mix business logic into your templates or to write unmaintainable code, but it doesn't go out of its way to encourage modularity or cleanliness either. For larger projects, meaning either lots of templates or several programmers, you may consider a more complex solution that enforces some rules. (Template Toolkit might be a good step up, read below.) But for quick and dirty (or quick and clean) templates, Text::Template is awesome. Also, if your application is <em>not</em> a web application, this is a good place to start.</p>

<h2>Perl Team, Web App: HTML::Mason</h2>

<p><a href="http://search.cpan.org/dist/HTML-Mason/">HTML::Mason</a> is an excellent solution for a small team of Perl programmers writing their own HTML. Although it is not limited to HTML (it works fine with any kind of text), Mason excels at web development. It ships with a light-weight web framework of its own, although it can also be plugged into web frameworks like <a href="http://catalyst.perl.org">Catalyst</a>. </p>

<p>Like Text::Template, Mason works by embedding Perl into your templates, so Perl programmers can pick it up fairly quickly. Much of Mason's added syntax is geared around triggering code at different points in the request cycle, and creating time-saving features like automatic wrapping of content with layout components that are "inherited" based on the directory hierarchy. </p>

<p>Mason allows you to think about HTML design like a <em>programmer</em>, decomposing a web site into reusable components that are effectively Perl objects, each with its own methods and variable scope. This makes it highly effective for code-centric applications, where the HTML is built after the primary program logic.</p>

<p>Mason is not necessarily the best system for HTML designers who are not Perl hackers. Because it encourages decomposition into components, you rarely have a template that represents a complete HTML document. Mason's syntax uses pseudo-tags to demarcate embedded logic, which tends to upset HTML-centric design tools.</p>

<p>I find Mason to be especially useful for applications where I need to create a web interface to some existing data store, such as a SQL database created by another application. Combined with a clean database access layer like <a href="http://search.cpan.org/dist/DBIx-Class/">DBIx::Class</a>, you can get from legacy database to structured web front-end extremely quickly.</p>

<p>I'm a big Mason fan, and I encourage you to visit <a href="http://www.masonhq.com">Mason HQ</a> to give it a try.</p>

<h2>Dedicated HTML Coder: HTML::Template or Template Toolkit</h2>

<p>If your team has designers who are good with mark-up but not experienced programmers, then you probably want a template system that will insulate them from program logic while giving them the flexibility to construct simple loops and conditionals. </p>

<p><a href="http://search.cpan.org/dist/HTML-Template/">HTML::Template</a> is a good choice for the mark-up coder who is less programmatically inclined. Its syntax is close to HTML, which flattens the learning curve, and it doesn't expose too many internal moving parts that would be hard to learn and easy to break. On the other hand, the syntax is <em>so</em> similar to HTML that HTML editing tools might see it as bad mark-up and complain about it. As with Mason, your templates will almost certainly not validate on their own. [UPDATE: As jerje pointed out in the comments, HTML::Template allows an alternate syntax that hides the template instructions in HTML comments, which allows them to validate.] As a programmer, I find the functional limitations frustrating.</p>

<p>If your HTML expert is also comfortable writing Javascript code (or some other non-Perl language like Java, Python, or Ruby), you might shift toward <a href="http://search.cpan.org/dist/Template-Toolkit/">Template Toolkit</a>. TT allows you to use program objects in the template using a Javascript-like dot syntax, and gives a bit more flexibility in logical constructs. TT also has the advantage that it can scale to large and complex template sets, and its numerous plugins give you a lot of usage options. Template instructions will not be confused with HTML mark-up, either by humans or editing tools, so if you're careful you can get your unprocessed templates to validate.</p>

<h2>Fancy-pants Designers vs. Engineers: Template Toolkit, Petal, Template::TAL</h2>

<p>If your web application is heavily design-oriented, what your designers want from you is probably what they might describe as "server-side Javascript". That is, you are probably working from a design first, and building program logic to hang functionality onto the design.</p>

<p>Template Toolkit can fit pretty well into this kind of process. It makes sense to designers familiar with Javascript or some other programming language, and the more programmatically inclined designers enjoy exercising program logic in their templates. But not all designers are programmatically inclined. I refer to these types (lovingly) as "fancy-pants" designers.</p>

<p>Typically, fancy-pants designers will start with a "wireframe" sketch and move up to fully elaborated Photoshop mocks of their web designs. Only after working in this form for several iterations will they start to generate an HTML model of the design. Their first goal is to create an HTML model that exactly mimics their Photoshop images, including sample text and images in the content areas. This helps them to visually prove that their designs will display correctly in a web browser (vitally important for a design-intensive web application).</p>

<p>Using Template Toolkit or any of the above template solutions adds a step to the design workflow where the HTML model must be dismantled, and bits of pretty HTML filler replaced with unattractive template tags and symbols. Most designers don't care for this, because it makes it more difficult to visualize the product as it was meant to be viewed. Design changes that come <em>after</em> this transformation can be painful, because the designers usually have to go back to their mocked HTML model to visualize the changes, and then they (or you) must repeat the dismantling and replacement process.</p>

<p><a href="http://search.cpan.org/perldoc?Petal">Petal</a> and <a href="http://search.cpan.org/perldoc?Template::TAL">Template::TAL</a> are potential solutions to this problem. (Both are Perl ports of a Python tool, <a href="http://wiki.zope.org/ZPT/TAL">Zope Template Attribute Language</a>.) Their technique solves the problem by hiding template instructions in the HTML as extra attributes on proper HTML tags. Designers can feel free to fill the template with sample text and images that will make the template display cleanly in any web browser or HTML editing tool. Instead of taking this filler away, they (or you) <em>add</em> template instructions that dictate how the filler should be replaced by the output of program objects when the template is processed. Using namespaces, this can result in templates that are valid XHTML documents.</p>

<h2>And the winner is...</h2>

<p>What have we learned? When choosing a template system, you must consider the needs of the team as a whole, not just the software developers. Any of these solutions might be perfect for your team and your workflow.</p>

<p>But since you insist: My personal favorite is <a href="http://search.cpan.org/dist/HTML-Mason/">HTML::Mason</a>. I've been using it to build web applications for years. The community is very supportive, I'm comfortable with it's quirks, and most importantly, I'm extremely productive with it. However, if you currently have no experience with any of these template systems, and you want to learn only <em>one</em> system, I recommend you pick up <a href="http://search.cpan.org/dist/Template-Toolkit/">Template Toolkit</a>. It has a vibrant community around it, which I consider a must for any tool I use. You can get started quickly. And you can reasonably use it in small, simple applications as well as large complex ones, so it leaves you plenty of room to grow.</p>

<p>If I forgot to mention <em>your</em> favorite template system, I'm sorry. I can only write about what I know, and these are the template systems that I am familiar with. Feel free to plug your own favorite solution in the comments!</p>
]]>
    </content>
</entry>

<entry>
    <title>Working widgets in MTOS</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2007/12/working-widgets-in-mtos.html" />
    <id>tag:www.webquills.net,2007:/scroll//1.17</id>

    <published>2007-12-28T16:17:21Z</published>
    <updated>2007-12-28T16:32:37Z</updated>

    <summary>Yesterday I upgraded Webquills.net to the &quot;Boxing Day&quot; build of MTOS. I was pleased to find that the widgetized sidebar is now activated for the default theme. I had tried (admittedly not very hard) to get the widgetized sidebar working...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
    <category term="mtos" label="MTOS" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>Yesterday I upgraded Webquills.net to the <a href="http://www.movabletype.org/opensource/nightlies/MTOS-4.1-en-release-26-r1120-20071226.tar.gz">"Boxing Day" build</a> of MTOS. I was pleased to find that the widgetized sidebar is now activated for the default theme. I had tried (admittedly not very hard) to get the widgetized sidebar working in a previous build, but all I got was empty space.</p>

<p>Actually, with the Boxing Day release, you still get empty space by default, because although the widgetized sidebar is enabled, the sidebar components aren't actually populated with any widgets.</p>

<p>Creating your own widgets works pretty much like you would expect. I created a Google AdSense widget just by pasting the AdSense code into a new widget and wrapping it in a couple of nested divs classed with "widget" and "widget-content" respectively, code that I copied from the pre-built widgets. I was also able to modify some existing widgets without any trouble.</p>

<p>But I see that a new nightly build is out, so this is probably old news. Still, I'm gratified to see steady progress being made. The nightly builds are firming up. Some people have reported intermittently about upgrade issues, so you'll probably want to wait for the stable release to upgrade an older Movable Type installation. If you're starting up a new blog, the nightly builds should prove good enough at this point.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Perl 5: The grass is plenty green</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2007/12/perl5-grass-is-plenty-green.html" />
    <id>tag:www.webquills.net,2007:/scroll//1.1</id>

    <published>2007-12-22T15:33:19Z</published>
    <updated>2007-12-22T15:36:32Z</updated>

    <summary>A few months ago I wrote a missive lamenting the coolness going on in other languages in terms of web frameworks and the dearth of magical leaps forward in Perl. Well, I take it all back. Serves me right for...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Misc" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Web Design" scheme="http://www.sixapart.com/ns/types#category" />
    
    <category term="framework" label="framework" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="webdev" label="webdev" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>A few months ago I wrote a missive lamenting the coolness going on in other languages in terms of web frameworks and the dearth of magical leaps forward in Perl. Well, I take it all back. Serves me right for not recognizing hype for what it is.</p>

<p>Each of the frameworks from other languages that I examined promised great leaps in productivity for programmers of that language. But what I came to realize was that these were improvements that I had <em>already</em> experienced in Perl. The streamlining did not come from the <em>language</em> at all. One scripting language, it seems, is pretty much as good as the next when it comes to productivity for the skilled programmer. No, the great leap forward came from applying a well organized web application development framework and its associated tools to the problem of web development, where before there had been no organized solution and only a rudimentary tool set.</p>

<p>But I have been using Perl web application frameworks for years. (I use the plural of framework because <abbr title="There Is More Than One Way To Do It">TIMTOWTDI</abbr> in Perl.) <a href="http://perl.apache.org">Apache+mod_perl</a> is an amazingly rich web application framework on its own. Perl was (I believe) the first scripting language to be embedded in the web server itself, and is still the best option for manipulating the rich, complex internals of Apache. <a href="http://www.masonhq.com">HTML::Mason</a>'s ApacheHandler is a simple layer on top of mod_perl that is a highly effective solution to certain classes of problems. Richer, more modern frameworks like <a href="http://catalyst.perl.org">Catalyst</a> and <a href="http://jifty.org">Jifty</a> do more for you, but also require you to do more learning to get productive. In Perl, we're spoiled for choice, which is a problem all its own. But the point is, the other scripting languages haven't beat Perl in the web framework race. They are just now catching up!</p>

<p>This is certainly not a call for Rails developers to switch to Perl. Why should they? The fact of the matter is that web frameworks in whatever language are substantially similar to one another, because they are each a solution to the exact same problem, built under similar constraints.</p>

<p>Programmers should use whatever language fits their mind best, because that is where they will find themselves most productive. For some people, that's Java. (Some people are <em>weird</em>.) For some its Python or Ruby. More power to you. But if you are productive in Perl, don't be lured away to some other language by the greener-looking grass on their side of the fence.The grass is plenty green right here.</p>

<p>Don't believe it? Subscribe to Webquills.net via <a href="http://feeds.feedburner.com/Webquills">RSS</a> or <a href="http://www.feedburner.com/fb/a/emailverifySubmit?feedId=929839&amp;loc=en_US">Email</a>
and learn all about it.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Wordpress to MTOS: An easy migration (so far)</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2007/12/wordpress-to-mtos.html" />
    <id>tag:www.webquills.org,2007:/scroll//1.16</id>

    <published>2007-12-18T21:07:51Z</published>
    <updated>2007-12-18T21:15:15Z</updated>

    <summary>With the recent and long-awaited release of Movable Type Open Source, I undertook to port my blog at Webquills.net to the new MTOS. Why MTOS? I&apos;ve never felt comfortable publishing my content in proprietary software. Even if I could obtain...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>With the recent and long-awaited release of <a href="http://www.movabletype.org/opensource/">Movable Type Open Source</a>, I undertook to port my blog at Webquills.net to the new MTOS.</p>

<h2>Why MTOS?</h2>

<p>I've never felt comfortable publishing my content in proprietary software. Even if I could obtain it gratis, I was always paranoid that the license would change out from under me and I would suddenly find myself in a panic trying to port my content to some other system. So I started blogging on the GPL-licensed <a href="http://www.wordpress.org/">Wordpress</a>, and I liked it well enough.</p>

<p>I am a Perl programmer by trade, and though my PHP skills are reasonably good, I would feel much more comfortable hacking on Perl code. MTOS is written in Perl so it gets points. That's my first reason for switching.</p>

<p>My second and more pressing reason to switch to MTOS is its static publishing model. I run my blog on a web server that's light on memory, and what memory there is, I like to use for my own web development. Using a heavy Apache/PHP process to serve a page whose content has not changed in weeks is a luxury that I'd rather not have to pay for. I'm willing to trade slightly delayed publishing for lightweight static file serving.</p>

<h2>Installing MTOS</h2>

<p>Installing MTOS was pretty simple. Not <em>quite</em> as simple as installing Wordpress, but simple enough that anyone comfortable with a Unix shell (or well-skilled with their FTP client) can get it done without breaking a sweat.</p>

<p>Be warned, however, that as of this writing no "stable" builds of MTOS have been released. I'm using one of the nightly builds, and it works fine for me, but you may run into some issues. If that bothers you, stick with the commercial version until the first MTOS stable release comes out.</p>

<p>I pretty much followed the <a href="http://www.movabletype.org/documentation/installation/detailed-instructions.html">installation instructions</a> for Linux. I created a MySQL database for MTOS to use, and a new user with full permissions on the database. Then I grabbed the latest nightly build from the <a href="http://www.movabletype.org/opensource/nightlies/">MovableType.org archive</a>. Simply untarring it into my chosen destination was enough to get started. Then I walked through the "install wizard" filling in the blanks as needed. None of the questions were particularly tough to answer. :)</p>

<p>After completing the installation, I got some warnings that MTOS did not have permission to write to the <code>/mt-static/support/</code> directory. Apparently this is where MTOS stores uploaded files and its own reports. I did a <code>chown www-data mt-static/support</code> so the web server could write there, and the complaints went away. I also had to do this to the output directory where I told MTOS to write my blog.</p>

<h2>Migrating the content</h2>

<p>The step that surprised me the most was migrating my Wordpress content to MTOS. It was shockingly easy. I entered the Wordpress admin area and selected Manage -> Export from the menus. Pressed the button, and I have a Wordpress eXtended RSS feed (WXR file) containing all my posts, comments, and categories (and probably other stuff too).</p>

<p>Then I went to MTOS and clicked to System Overview -> Import. I set the type to WXR and uploaded my Wordpress data. Snap! Just like that MTOS had my posts, comments, and categories all sorted out and ready to use. I punched the publish button and had a web site ten seconds later.</p>

<h2>Final cleanups</h2>

<p>I picked the most boring MTOS style I could find (because a blog should resemble its owner :P), and made just one customization. I wanted to point users to my <a href="http://www.feedburner.com">FeedBurner</a> feed instead of the local one. I picked Design -> Templates from the menu, then picked Template Modules and edited the Header module. I also had to change the "subscribe" link in the Sidebar modules. (Well, it wasn't as easy as it sounds. It took ten minutes of clicking around to find the right bit to edit. Still, it wasn't exactly <em>hard</em>, either.)</p>

<p>That done, I republished, and was ready to go.</p>

<p>The trickiest part of the migration had little to do with either Wordpress or Movable Type. It was simply that the URLs for my blog entries were going to change under the new system. But <a href="http://www.w3.org/Provider/Style/URI.html">cool URIs don't change</a>, so I needed to create a translator for the old ones. I handled this using a simple Apache directive with some Regex Fu.</p>

<pre><code> RedirectMatch permanent ^/(\d\d\d\d/\d\d/[^/]*)/?$ \
http://www.webquills.net/scroll/$1.html
</code></pre>

<h2>More to come?</h2>

<p>I'll probably publish some more comments about MTOS as I get used to using and customizing it. In the interim, I can say that the migration process from Wordpress to MTOS is surprisingly easy and should not be considered an excuse for not switching!</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Forking Perl</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2007/11/forking-perl.html" />
    <id>tag:www.webquills.org,2007:/scroll//1.15</id>

    <published>2007-11-16T12:11:51Z</published>
    <updated>2007-12-15T21:43:21Z</updated>

    <summary>One of my favorite sites, Perl Buzz, just pointed me to Kurila, an experimental Perl 5 fork. I&apos;m not sure how I feel about that. On the one hand, I do love to see innovation in the Perl space. Perl...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>One of my favorite sites, <a href="http://perlbuzz.com">Perl Buzz</a>, just pointed me to <a href="http://perlbuzz.com/2007/11/gerard-goosen-talks-about-kurila-a-perl-5-fork.html">Kurila, an experimental Perl 5 fork</a>. I'm not sure how I feel about that. On the one hand, I do love to see innovation in the Perl space. Perl 6 has been promised by Christmas, they just won't say what year. I figure 2014. But Perl 6 isn't Perl anyway, it's a new language in (tattered) Perl clothing. Perl 5 marches on in 5.10, though, which keeps me from complaining too much.</p>

<p>On the other hand, I would hate to see Perl stagnate so much that a fork like this actually became a viable alternative for the average Perl developer. Not because the fork is bad code or has bad language implications (on the contrary, I like some of Karila's ideas), but because of what that would mean about the <em>old</em> Perl. Namely, that it started to suck worse than the alternatives.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Movable Type Open Source - again</title>
    <link rel="alternate" type="text/html" href="http://www.webquills.net/scroll/2007/06/movable-type-open-source-again.html" />
    <id>tag:www.webquills.org,2007:/scroll//1.14</id>

    <published>2007-06-20T03:08:25Z</published>
    <updated>2007-12-15T21:43:20Z</updated>

    <summary>[UPDATE: I stand corrected. Informed commenters point out that though the source was available, MT was never technically &quot;open source&quot;. To quote Richard Blain, &quot;I was misinformed&quot; -V] It&apos;s ironic, to me at least. When I first got interested in...</summary>
    <author>
        <name>Vince V.</name>
        
    </author>
    
        <category term="Blogging" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Misc" scheme="http://www.sixapart.com/ns/types#category" />
    
        <category term="Perl" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.webquills.net/scroll/">
        <![CDATA[<p>[UPDATE: I stand corrected. Informed commenters point out that though the source was available, MT was never technically "open source". To quote Richard Blain, "I was misinformed" -V]</p>

<p>It's ironic, to me at least. When I first got interested in blog software, I heard that Movable Type was the one to beat. It was written in Perl, which was my language of choice; <strike>it was open source (so you could make your own modifications)</strike>; and it was by many accounts the most advanced blogging software out there (but not without argument, of course, this is the Internet).</p>

<p>Five minutes after I discovered it, the company announced that their 3.0 version would carry a new, commercial license. Suddenly being Perl was useless, because I could no longer modify, fork, or crib from the code. I moved on, and finally settled on Wordpress.</p>

<p>Now, Movable Type is <strike>once again</strike> <a href="http://www.movabletype.org/opensource/">opening its source code</a>. Thanks to Ben and Mena for contributing this code back to the community. Ultimately, open source software is not about the software, it's about the community of users, and we users appreciate it when the companies we support share with us. Keep up the good work!</p>
]]>
        

    </content>
</entry>

</feed>
