<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Perlblogs &#187; languagedesign</title>
	<atom:link href="http://perlblogs.com/category/languagedesign/feed/" rel="self" type="application/rss+xml" />
	<link>http://perlblogs.com</link>
	<description>Posts from selected Perl bloggers</description>
	<lastBuildDate>Fri, 18 May 2012 19:03:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>use_ok() is Broken Because require() is Broken</title>
		<link>http://www.modernperlbooks.com/mt/2012/04/use-ok-is-broken-because-require-is-broken.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/04/use-ok-is-broken-because-require-is-broken.html#comments</comments>
		<pubDate>Wed, 11 Apr 2012 17:30:09 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[bugs]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=476f6a88daba3457743ffd99bb0861b4</guid>
		<description><![CDATA[Ovid's post on avoiding Test::More's use_ok() is good advice. There's almost no reason to use use_ok() from Test::More in existing code. It probably doesn't do what you think it does, and it doesn't really help against most of the failures...]]></description>
			<content:encoded><![CDATA[
        <p>Ovid's post on <a
href="http://blogs.perl.org/users/ovid/2012/04/avoiding-use-ok-in-t00-loadt.html">avoiding
Test::More's use_ok()</a> is good advice. There's almost no reason to use
<code>use_ok()</code> from <a
href="http://search.cpan.org/perldoc?Test::More">Test::More</a> in existing
code. It probably doesn't do what you think it does, and it doesn't really help
against most of the failures you probably care about.</p>

<p>Worse, it can give you a false sense of security and mislead you into
debugging the wrong thing.</p>

<p>Why? Because it turns what ought to be a fatal, program-killing exceptional
condition ("Hey, I couldn't load this module! I'd better stop now. Things are
certainly not going to work the way anyone expects!") into a simple failed test
("Oopsie! Better check your assumptions! I'll keep going though, because
hopefully you just made a typo in your test assertion!").</p>

<p>The problem really isn't with <code>use_ok()</code> though. The problem's
with Perl 5's <a
href="http://perldoc.perl.org/functions/require.html">require</a>.</p>

<p><code>require</code> does one thing. It searches the filesystem for the
named file, compiles it, and caches the success or failure of compilation.
(Make that three things.)</p>

<p>Here's the problem: what if compilation fails? What of compilation fails
halfway through the file? What if compilation fails on the very last line of
the file because the module doesn't return a true value? Try it yourself:</p>

<pre><code>package FalseReturnValue;

sub demo { 'demo' }
sub demo2 { 2 }

0;</code></pre>

<p>... and the test:</p>

<pre><code>use Test::More;

use lib 'lib';
use_ok( 'FalseReturnValue' );

is FalseReturnValue::demo(), 'demo', 'Declared functions exist';
is FalseReturnValue::demo2(), 2,     '... all of them';

done_testing;</code></pre>

<p>The problem is that failing to load a module should never leave your system
in an inconsistent state.</p>

<p>Getting this right is very, very difficult. Getting this right means not
committing anything to globally visible symbols until you're certain that the
module compiled correctly. For a module like <code>FalseReturnValue</code>,
that's easy. For a module which itself uses something like Catalyst or
DBIx::Class with several dependencies, this is tricky.</p>

<p>The best approach I can think of is to maintain some sort of transactional
system (yes, I know it sounds awfully complex, but you asked for correctness
first, so humor me through at least this sentence) where you build up a set of
changes to globally visible symbols and then only apply that delta if that
compilation as a whole&mdash;the top-level module and all of its
dependencies&mdash;succeeds.</p>

<p>The second best solution is to do that for each module. It's all or nothing
for each <code>use</code> statement on its own, regardless of how far down the
dependency tree you are.</p>

<p>(You could go one step further and make everything anonymous by default,
such that the only way you can access package global symbols in another
namespace is by binding to that namespace explicitly, but that's a bigger
change with implications on code reuse and the cross cutting concerns of an
object system, even though it does have the potential to clean up things like
accidental exports.)</p>

<p>Of course, if your worldview has already said that failing to load a
dependency with <code>use</code> should abort the program with red flashing
klaxon lights and a siren, you don't have to do that much work.</p>

<p>(... but <code>require</code> errors are exceptions you can catch with
<code>eval { ... }</code>, so the problem remains with
<code>require</code>.)</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/04/11/use_ok-is-broken-because-require-is-broken/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Consistency, CPAN, and Captiousness</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/consistency-cpan-and-captiousness.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/consistency-cpan-and-captiousness.html#comments</comments>
		<pubDate>Tue, 27 Mar 2012 19:15:35 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=7be7a53dd7c6d05ed4a8c4426938514d</guid>
		<description><![CDATA[Once in a while, an innocent looking change to bleadperl (the version of Perl 5 under current development) causes changes which ripple through the CPAN. As the CPAN is a graph of dependencies, any such change which causes tests to...]]></description>
			<content:encoded><![CDATA[
        <p>Once in a while, an innocent looking change to bleadperl (the version of Perl 5 under current development) causes changes which ripple through the CPAN. As the CPAN is a graph of dependencies, any such change which causes tests to fail could have dramatic effects on user applications.</p>

<p>(Once I almost released a change which would have made half of CPAN uninstallable. Then Schwern slapped my hand metaphorically.)</p>

<p>Sometimes the fault isn't in bleadperl.</p>

<p>Consider <a href="https://rt.perl.org/rt3//Public/Bug/Display.html?id=106538">RT #106538</a>, which laments the inconsistency between the output of the builtin <code>die</code> and <a href="http://search.cpan.org/perldoc?Carp">Carp</a>'s <code>croak()</code>. From the bug report:</p>

<pre><code>$ <strong>perl -e 'die'</strong>
Died at -e line 1.
$ <strong>perl -MCarp -e 'croak Died'</strong>
Died at -e line 1</code></pre>

<p>If your eyes don't immediately catch the missing period, you're in good
company.</p>

<p>Consistency suggests that the output of both error messages should be
identical. After all, <code>Carp</code> exists to enhance Perl 5's core
exception mechanisms.</p>

<p>Yet as you might expect, <a
href="http://www.modernperlbooks.com/mt/2010/08/the-stringceptional-difficulty-of-changing-error-messages.html">changing
error messages breaks buggy code that attempts to parse unstructured text too
strictly</a>. Adding a single dot to an error message makes several important
CPAN modules fail their tests.</p>

<p>I can't blame CPAN developers for performing exact matches against string error messages&mdash;it's quick and easy and unlikely to change, and it's reasonably easy to fix... until you get a fix that looks like:</p>

<pre><code>$pattern .= $Carp::VERSION gt "1.24" ? "." :"";</code></pre>

<p>... which <em>knows</em> that the period is present but <em>persist in
hard-coding specific formatting details of the output</em>.</p>

<p>The right solution, of course, is to stop emitting only unstructured text
(from the core side) and to stop testing the exact details of unstructured text
(on the CPAN side). The interim solution is to stop testing the exact details
of unstructured text on the CPAN side.</p>

<p>Despite all of the effort around what could have been a simple change, the
entire process of developing Perl 5 is a huge improvement over its past. Making
this change and identifying its effects was reasonably easy, when you consider
the size of the task and its consequences. Sure, the entire Perl community has
to pay off some of the technical debt for well-established choices and design
decisions that turned out to have been less than perfect, but this is a good
opportunity to see how much better things are than they were even five years
ago and to reflect on how to improve processes and tools to make them better as
early as next year.</p>

<p>Do keep in mind, however, that if you're performing exact string matches
against the results of things the core has never promised not to change, you
are writing risky code.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/27/consistency-cpan-and-captiousness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inadvertent Inconsistencies: each versus Autoderef</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-versus-autoderef.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-versus-autoderef.html#comments</comments>
		<pubDate>Fri, 23 Mar 2012 16:33:31 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=8a9f693c7df1ae21c5e729df3203a5c8</guid>
		<description><![CDATA[Perl 5.12 allows you to use each, keys, and values on arrays. Perl 5.14 will automatically dereference references used as operands to the aggregate operators. The combination produces a worrisome inconsistency. Perl 5.12's each had no obvious inconsistency problem; you...]]></description>
			<content:encoded><![CDATA[
        <p><a
href="http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html">Perl
5.12 allows you to use <code>each</code>, <code>keys</code>, and
<code>values</code> on arrays</a>. <a
href="http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-aggregate-autoderef-in-514.html">Perl
5.14 will automatically dereference references used as operands to the
aggregate operators</a>. The combination produces a worrisome
inconsistency.</p>

<p>Perl 5.12's <code>each</code> had no obvious inconsistency problem; you had
to write <code>each @$kittens</code> or <code>each @{ $kittens }</code> when
using an array reference as its operand. Sure, you could write <code>each %{
$kittens }</code> when <code>$kittens</code> holds an array reference, but
you'll get an error when the program runs like you would for dereferencing the
wrong type of reference anyway.</p>

<p>With Perl 5.14, you have the curious situation where it's possible to give
one of these polymorphic aggregate operators an operand which can behave
<em>both</em> as a hash and as an array. By <a
href="http://search.cpan.org/perldoc?overload">overload</a>ing an object, you
can make it respond to array operations, or hash operations, or both.</p>

<p>If you use one of these objects as the operand to <code>each</code>,
<code>keys</code>, or <code>values</code>, what is Perl to do? It's easy to
test:</p>

<pre><code>use Modern::Perl;

package DestroyerOfHope;

use overload
    '%{}' =&gt; \&gethash,
    '@{}' =&gt; \&getarray;

sub new
{
    my $self = shift;
    bless [qw( I am an array )], $self;
}

sub gethash  { { I =&gt; 'hash' } }
sub getarray { $_[0] }

package main;

my $d = DestroyerOfHope-&gt;new;
say each $d;</code></pre>

<p>As of Perl 5.14, you get a runtime error "Type of argument to each on
reference must be unblessed hashref or arrayref...". (The rationale was partly
"Uh oh, this could go wrong!" and partly "Why would you want to iterate over
something blessed?" The latter seems to me to ignore the fact that blessing is
the only way to produce this kind of desirable overloading, but that's an
argument for another time.)</p>

<p>While that decision certainly closes the door on this type of error, it's
hardly the only way to solve this inconsistency. I see five other options:</p>

<ul>

<li>Forbid autodereferencing on operands with any overloading</li>

<li>Always choose one overloading over the other (array always wins! hash always wins!), preferably producing a run-time warning</li>

<li>Forbid autodereferencing on operands with both types of overloading, giving a run-time error</li>

<li>Forbid autodereferencing with <code>each</code>, <code>keys</code>, and <code>values</code></li>

<li>Revert the polymorphism of <code>each</code>, <code>keys</code>, and <code>values</code></li>

</ul>

<p>Keeping the existing behavior is probably the easiest, but it has two
problems. First, it's inconsistent with Perl's nature. Sure, <a
href="http://www.modernperlbooks.com/mt/2011/03/a-mop-for-perl-516.html">Perl
deserves opaque objects</a>, but what we have now are blessed references. Why
are some references autodereferenceable and others not (especially in the
presence of <code>overload</code>? Second, the existing behavior papers over a
real problem. The interaction of these two features is <em>inconsistent</em>
because one of the features ignores a longstanding design principle of Perl.</p>

<p>The real problem was making <code>each</code>, <code>keys</code>, and <code>values</code> work on arrays as well as hashes.</p>

<p>I understand the desire to make this feature work. It's easy to say "I want
something like <code>each</code> that works on arrays!" The obvious next step
is to expand that feature to include other hash aggregate operators. (The
pursuit and implementation of a small consistency is easy. The pursuit and
implementation of a language-wide consistency is very difficult.)</p>

<p>It's also much easier to hang new behavior off of existing keywords than it
is both to find the right new keyword and to add a new keyword (<a
href="http://www.modernperlbooks.com/mt/2009/06/yagni-badvocacy-and-the-perlian-knot.html">adding
new keywords is a perilous process</a>). Would <em>you</em> want to type
<code>while (my ($index, $value) = arrayeach $kittens) { ... }</code> every
time you wanted to iterate over an array and get its index and value? Probably
me neither.</p>

<p>Yet the problem remains. By making <code>each</code>, <code>keys</code>, and
<code>values</code> polymorphic with respect to the types of their operands,
Perl 5 has removed its ability to provide greater consistency across the
language. (It's not just for the compiler; it's for people <em>reading</em> the
code.)</p>

<p>The purest response, from the point of view of language design, is to
deprecate the use of hash aggregates on anything but hashes and to find new
keywords to perform the same functions on arrays. Enabling the feature set of
Perl 5.12 or Perl 5.14 (or, by now, Perl 5.16) could re-enable this polymorphic
behavior, but p5p could contain the damage to those releases alone and provide
better options in the future.</p>

<p>The practical response is to acknowledge yet another wart on the language
and keep the existing warning.</p>

<p>In user code, the best option is probably to avoid autodereferencing
altogether, even as tempting as it seems. (This is a controversial statement,
but I believe it's probably better to avoid the temptation to use a feature
when the human brain's desire for pattern recognition and consistency may lead
you down a path to using the inconsistent operators, and then where will you
be?)</p>

<p>What's the solution in the future to avoid further inconsistencies like
this? Always hew to Perl 5's fundamental principles. (Note that the biggest
problem with the controversial and soon-to-be-bowdlerized smartmatch operator
is that it also is a polymorphic operator and no one can memories exactly what
it does in every common situation, let alone every edge case.)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/23/inadvertent-inconsistencies-each-versus-autoderef/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inadvertent Inconsistencies: Aggregate Autoderef in 5.14</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-aggregate-autoderef-in-514.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-aggregate-autoderef-in-514.html#comments</comments>
		<pubDate>Wed, 21 Mar 2012 19:18:58 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=3ca6c579d034c55837cb35477d785526</guid>
		<description><![CDATA[Perl 5's dereferencing syntax has always been ugly. It's perhaps the ugliest part of the language's syntax. (Some people think regular expressions are ugly. They are, but they have a long history of being ugly. You don't blame the human...]]></description>
			<content:encoded><![CDATA[
        <p>Perl 5's dereferencing syntax has always been ugly. It's perhaps the ugliest
part of the language's syntax. (Some people think regular expressions are ugly.
They are, but they have a long history of being ugly. You don't blame the human
knee for being unattractive when it does what it does as effectively as it
does, but you also don't reproduce its ugliness when you design an entirely new
lifeform.)</p>

<p>Perl 5's aggregate operators (such as <code>push</code> and
<code>shift</code>) have traditionally required dereferencing when used on
aggregate operands. In other words, through most of Perl 5's lifespan you had
to write:</p>

<pre><code>my $diversions = [ 'Halo', 'LoTR Pinball', 'Cat Herding', 'Mario Galaxy' ];

my $evening_event = <strong>shift @$diversions</strong>;
# or <strong>shift @{ $diversions }</strong></code></pre>

<p>The same goes for hash operators:</p>

<pre><code>my $pet_nicknames =
{
    Lucky  => 'Stinkerbell',
    Rodney => 'Robot Parade',
    Choco  => 'Destructo Junior',
};

my @nicknames = values <strong>%$pet_nicknames</strong>;
# or values <strong>%{ $pet_nicknames }</strong></code></pre>

<p>Although Perl can warn you when you mention the wrong variable if you use
first-class aggregates (writing <code>keys %not_a_hash</code> when there's no
hash called <code>%not_a_hash</code> in scope, for example), you have no such
protection at the point of compilation when you dereference aggregate
references. If <code>$pet_nicknames</code> turns out not to be a hash, you get
a runtime error.</p>

<p>That's all well and good; we've lived with that through Perl 5's lifespan
and we know how to deal with that. Keep that in mind, though.</p>

<p>Perl 5.14 added a feature by which Perl will do what you mean when you
provide a scalar as the operand to one of these aggregate operators. In other
words:</p>

<pre><code>my @nicknames = values <strong>$pet_nicknames</strong>;
my $evening_event = <strong>shift $diversions</strong>;</code></pre>

<p>Because it's unambiguous that <code>shift</code> must operate on an array,
Perl will happily now dereference <code>$diversions</code> as if it were an
array. If it isn't an array, you get the same error that you'd have received if
you'd written <code>@{ $diversions }</code> or <code>@$diversions</code> on
something that isn't an array.</p>

<p>Removing extraneous superfluous bletcherous syntax is generally a good
thing, if it's truly unnecessary and unambiguous. In the case of array
operators, it is.</p>

<p><a
href="http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html">Then
we come to hashes</a>.</p>

<p>As of Perl 5.12, the hash operators work also on arrays. Again, that's
usually okay. If you write <code>each $diversions</code> or <code>values
$diversions</code> or even <code>keys $diversions</code> (though why would you
do either of the latter? <a
href="http://web.cn.edu/kwheeler/gram_parallelism.html">rhetoric
parallelism</a> in Perl poetry?), you'll get something sensible back...</p>

<p>... except that you don't get the protection you'd get if you'd written
<code>%{ $diversions }</code> or <code>%$diversions</code> when
<code>$diversions</code> is an array reference.</p>

<p>Obviously making <code>shift</code> and <code>push</code> autodereference
aggregates implies making the other array operators autodereference aggregates,
and making the array operators autodereference aggregate implies making the
hash operators autodereference aggregates. Consistency is a good thing.</p>

<p>Yet the combination of these two features in two Perl releases has produced
an inadvertent inconsistency such that using these features together is a
little bit less safe than not using them.</p>

<p>This isn't the worst of it; the next post will explain how things can go
worse, how to avoid these problems in your code, and how they could have been
avoided at the design and implementation levels&mdash;and why they weren't.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/21/inadvertent-inconsistencies-aggregate-autoderef-in-5-14/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inadvertent Inconsistencies: each in Perl 5.12</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html#comments</comments>
		<pubDate>Mon, 19 Mar 2012 16:37:37 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[perl512]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=bf53327a8987196941f4df54fa0856af</guid>
		<description><![CDATA[The explanation of changes in Perl 5.12 includes an innocent looking entry. In its entirety, it reads: each, keys, values are now more flexible &#38;nbsp;&#38;nbsp;The each, keys, values function can now operate on arrays. While there's often little use to...]]></description>
			<content:encoded><![CDATA[
        <p>The <a href="http://perldoc.perl.org/perl5120delta.html">explanation of changes in Perl 5.12</a> includes an innocent looking entry. In its entirety, it reads:</p>

<blockquote><code>each</code>, <code>keys</code>, <code>values</code> are now more flexible
&nbsp;&nbsp;The <code>each</code>, <code>keys</code>, <code>values</code> function can now operate on arrays.</blockquote>

<p>While there's often little use to using <code>keys</code> and
<code>values</code> on arrays, <code>each</code> has one fantastic use: managed
iteration over an array which provides access both to the index of the
iteration and the current iterator value:</p>

<pre><code>my @chapters = get_chapters( ... );

while (my ($number, $chapter) = each @chapters)
{
    say "Chapter $number: ", $chapter->title;
}</code></pre>

<p>This <em>feature</em> is great, especially when walking over multiple arrays
in parallel, or any time you want to let Perl handle the little details it
already tracks for you (instead of having to write <a
href="http://www.modernperlbooks.com/mt/2009/11/from-novice-to-adept-functional-versus-structural-code.html">unnecessary
structural code</a>).</p>

<p>Repurposing <code>each</code> (and <code>keys</code> and <code>values</code>) to work on arrays as well as hashes has benefits and drawbacks. There are no conflicts with user-defined functions, as these keywords have existed for longer than I've been using Perl. Semantically they perform somewhat similar functions, even though the aggregates on which they work are different.</p>

<p>The main drawback is that the operators themselves have to become polymorphic, in the sense that their behavior depends on the type of data provided.</p>

<p>We take it for granted that Perl does the right thing when we use
<code>==</code> to compare numbers for equality and <code>eq</code> to compare
strings for equality. That's why we use <code>.</code> to concatenate strings
in Perl 5 and <code>+</code> to add numbers; we make our intent
unambiguous.</p>

<p>(If you've never understood monomorphic operators and the degree to which
they <em>prevent</em> errors and <em>express programmer intent</em> in Perl,
the <a href="http://onyxneon.com/books/modern_perl/index.html">Modern Perl
book</a> includes an explanation of type contexts intended to make these ideas
clear. It's free to download and to redistribute.)</p>

<p>Is this change in operator philosophy a problem? Not by itself.</p>

<p>Next time: Perl 5.14 adds a feature.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/19/inadvertent-inconsistencies-each-in-perl-5-12/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Templating with Widgets, Not Primitives</title>
		<link>http://www.modernperlbooks.com/mt/2012/02/templating-with-widgets-not-primitives.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/02/templating-with-widgets-not-primitives.html#comments</comments>
		<pubDate>Thu, 09 Feb 2012 18:52:50 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[webprogramming]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=39c0fa5cf1f6b54db8631ed41e9215c0</guid>
		<description><![CDATA[After a disastrous attempt to write my own templating language as about the third program I ever wrote in Perl (it was the dot-com boom of the '90s, not that that's any excuse), I moved to Template::Toolkit and have been...]]></description>
			<content:encoded><![CDATA[
        <p>After a disastrous attempt to write my own templating language as about the
third program I ever wrote in Perl (it was the dot-com boom of the '90s, not
that that's any excuse), I moved to <a
href="http://search.cpan.org/perldoc?Template">Template::Toolkit</a> and have
been relatively happy with it ever since.</p>

<p>My first real paid programming job was a little GUI app for a customer
service group at HP. Customer service agents who needed to escalate to second
line support would click on the button for the printer line about which they
had to ask a question, and the program recorded the vote, then printed a nice
report at the end of the day. It solved a problem. As far as I know, it was
still running when I left HP a couple of years later.</p>

<p>A couple of years later, I took a job where we refactored, maintained, and
extended a GUI point of sale system.</p>

<p>Since then, I've avoided most graphical programming. Sure, I put together
websites for clients once in a while, but most of my work has been emitting the
most basic semantically-useful HTML possible such that a Real Designer can
manipulate things with CSS (CSS being, of course, one of those
so-horrible-it's-almost-good things in that it's the only way to get things
done, but you always want to take a shower after you use it, lest you think you
start to appreciate it for anything other than its efficacy. See also
JavaScript and PHP.).</p>

<p>Most of this meant dropping a big blob of content in a Template Toolkit
wrapper in the middle of some HTML, or maybe templatizing some repeated HTML
element while iterating over a collection in the toolkit.</p>

<p>Then I decided to redesign a site.</p>

<p>Twitter has its problems (I hope never to understand how or why someone
would take a perfectly functional website then try to make it work like a buggy
phone app in the same way that I never understood why the first Harry Potter
movie hewed so closely to the book it was as boring as a Merchant and Ivory
movie and it had <em>wizards</em> in it), but <a
href="http://twitter.github.com/bootstrap/">Twitter's Bootstrap</a> CSS
framework actually made sense to me, and it let me put together a couple of
pages that looked good&mdash;far better than the Frankenstein's monster I
cobbled together from the "Hey, everything's a blog now, right?" OSWD designs I
liked.</p>

<p>(Bootstrap has its problems too, but the worst one is that the <a
href="http://lesscss.org/">Less CSS</a> abstraction layer of CSS is intricately
tied to the Lovecraftian bonepile of crazy that is Node.js, because if there's
anything I want to do in JavaScript less than write a templating system to
perform text substitutions in a cooperative multitasking system, I don't know
what it is. It probably involves sharks, skydiving, live volcanoes, and dental
work. Yet even only being able to extract repeated <em>colors</em> into named
variables and build a static CSS file is a <em>huge</em> improvement, so I put
on protective eyeware.)</p>

<p>The experience turned out relatively enjoyable. I had a nice looking wrapper
and a decent framework for displaying and managing content.</p>

<p>Then I wanted to change the way I displayed certain elements.</p>

<p>Here's the thing about web programming, or at least the way I'm doing this
project. I don't think in terms of pages. I think in terms of components of
pages. I have a <em>templates/components/</em> directory full of reusable
Template Toolkit components processed with <code>INCLUDE</code> and
<code>PROCESS</code>. The big blurbs of marketing text and instructions and
explanations on various pages all live in individual components. Sure, it's a
little bit of work to figure out the layout, but this separation of concerns
makes editing the site much easier.</p>

<p>It also makes revising the layout more difficult&mdash;if changing the
layout requires modifying lots of templates with the wrong
<code>&lt;div&gt;</code> names and classes and such.</p>

<p>It's possible to write more TT components to abstract away these changes,
but the point of diminishing returns appears quickly: TT's syntax and semantics
just aren't strong enough to define functions and manage parameters.</p>

<p>Good thing Perl is.</p>

<p>Fewer than 20 minutes after I realized I needed a custom plugin, I had it
written:</p>

<pre><code>package MyProject::Template::Plugin::Bootstrap;
# ABSTRACT: basic Bootstrap helpers for the Template system

use Modern::Perl;

use parent 'Template::Plugin';

sub new
{
    my ($class, $context, @params) = @_;

    $class-&gt;add_functions( $context );

    return $class-&gt;SUPER::new( $context, @params );
}

sub add_functions
{
    my ($class, $context) = @_;
    my $stash             = $context-&gt;stash;

    for my $function (qw( row sidebar sideblock maincontent fullcontent span ))
    {
        $stash-&gt;set( $function, $class-&gt;can( $function ) );
    }

    $stash-&gt;set( process =&gt; sub { $context-&gt;process( @_ ) } );
}

sub row
{
    return &lt;&lt;END_HTML;
&lt;div class="row"&gt;
    @_
&lt;/div&gt;
END_HTML
}

sub sidebar
{
    return &lt;&lt;END_HTML;
&lt;div class="span4"&gt;
    @_
&lt;/div&gt;
END_HTML
}

sub sideblock
{
    return &lt;&lt;END_HTML;
&lt;div class="well"&gt;
    @_
&lt;/div&gt;
END_HTML
}

sub maincontent
{
    return &lt;&lt;END_HTML
&lt;div class="span8 maincontent"&gt;
    &lt;div class="hero-unit"&gt;
        @_
    &lt;/div&gt;
&lt;/div&gt;
END_HTML
}

sub fullcontent
{
    return &lt;&lt;END_HTML
&lt;div class="maincontent"&gt;
    &lt;div class="hero-unit"&gt;
        @_
    &lt;/div&gt;
&lt;/div&gt;
END_HTML
}

sub span
{
    my $cols = shift;
    return &lt;&lt;END_HTML;
&lt;div class="span$cols"&gt;
    @_
&lt;/div&gt;
END_HTML
}

1;</code></pre>

<p>This turned my templates into:</p>

<pre><code>
[% USE Bootstrap %]

[% row(
    maincontent( process( 'components/content/home_text.tt' ) ),
    sidebar(
        sideblock( process( 'components/forms/login_box.tt' )),
        sideblock( process( 'components/boxes/top_recommendation.tt' ) ),
        sideblock( process( 'components/content/newsletter_text.tt' ) ),
    ),
) %]</code></pre>

<p>This reminds me a bit of <a
href="http://www.seaside.st/documentation/generating-html">Generating HTML from
Smalltalk's Seaside</a> or <a href="http://haml-lang.com/">Ruby HAML</a>,
except it's less "Wow, lots of tags here!" than Seaside and "So cute people
hate you for saying how ugly it is!" than HAML.</p>

<p>I haven't convinced myself I have the right abstractions yet&mdash;it's not
quite to the point of the semantics I like, it produces its own repetitions,
and the idea of returning strings of HTML from a template plugin feels a little
wrong to me, but the big advantage is that it's taken a lot of repetitive
niggly code and turned it into less code that's much more declarative. The
repetition is in the <em>structure</em> of the <em>semantics</em> of the site
and not the mechanics of how to produce those semantics.</p>

<p>In other words, this is a step toward thinking in widgets rather than UI
primitives.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/02/09/templating-with-widgets-not-primitives/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Practical Use for Macros in Perl</title>
		<link>http://www.modernperlbooks.com/mt/2012/02/a-practical-use-for-macros-in-perl.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/02/a-practical-use-for-macros-in-perl.html#comments</comments>
		<pubDate>Fri, 03 Feb 2012 20:46:43 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[refactoring]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=5cffcd700874d4b530e9c045dc4412b1</guid>
		<description><![CDATA[People occasionally ask for practical examples of macros when I lament the lack of macros in Perl 5. While I'm usually pleased at the degree to which Perl lets me design code to get and stay out of my way,...]]></description>
			<content:encoded><![CDATA[
        <p>People occasionally ask for practical examples of macros when I lament <a
href="http://www.modernperlbooks.com/mt/2011/11/what-the-perl-5-compiler-modules-could-have-been.html">the
lack of macros in Perl 5</a>. While I'm usually pleased at the degree to which
Perl lets me design code to get and stay out of my way, sometimes its
abstractions just aren't quite <em>enough</em> enough to remove all of the
duplication available.</p>

<p>(I've been refactoring one of our business projects in preparation for another round of deployment in the next couple of weeks. We could launch without these improvements, but administrative work took almost two weeks longer than the afternoon I'd planned for it, so I decided it was worth my time to <a href="http://www.modernperlbooks.com/mt/2011/11/on-technical-friction.html">reduce technical friction</a> so that further improvements are easier. More users means more work, so why not accelerate that work while I have the chance? I have another longer technical post to write to praise the use of Moose roles for a plugin system and to show off the stupidly-great task launcher, but that's for later.)</p>

<p>I found myself writing two code couplets that were similar enough they
triggered my "Hey, refactor away this duplication!" alert. It's extra
sensitive, because I <em>know</em> I'll have a few more couplets like this in
the very near future:</p>

<pre><code>while (my $stock = $stock_rs-&gt;next)
{
    my $pe_update = $self-&gt;analyze_pe( $stock );
    $stock_txn-&gt;add( $pe_update ) if $pe_update;

    my $cash_yield_update = $self-&gt;analyze_cash_yield( $stock );
    $analysis_txn-&gt;add( $cash_yield_update ) if $cash_yield_update;
}</code></pre>

<p>The <code>*_txn</code> variables contain objects representing deferred and
scoped SQL updates. I'll talk about that at <a
href="http://act.yapcna.org/2012/">YAPC::NA 2012</a> in <a
href="http://act.yapcna.org/2012/talk/50">When Wrong is Better</a>.</p>

<p>The general pattern is this: for every stock in the appropriate resultset,
call a method in this plugin. The method will return nothing if it fails (or
has nothing to do) or it will return data to be added to the appropriate
transaction. I have at least two types of transactions available here at the
moment, and may have more later: one transaction updates stock data and the
other updates analysis data.</p>

<p>I have several options. I could rework the data model so that this stage
always only updates one transaction, in which the loop body could instead look
like:</p>

<pre><code>{
    for my $method (qw( analyze_pe analyze_cash_yield ))
    {
        next unless my $result = $self->$method( $stock );
        $txn->add( $result );
    }
}</code></pre>

<p>This technique of hoisting the variants into an ad hoc data structure and
using existing looping techniques works well sometimes. (I use it in other
parts of the system.) It's relatively easy to expand, even though it moves
interesting information ("I'm calling the <code>analyze_pe</code> method!") to
a place where tools have more trouble finding it. (I search for
<code>&gt;analyze_pe</code> when I want to find method calls.) You may have used something similar to define several parametric methods at <code>BEGIN</code> time. It's the same type of pattern, and while Perl 5 provides most of the tools necessary to allow this, it doesn't natively express this pattern well.</p>

<p>I could also change the transaction object's <code>add()</code> method to do
nothing when it receives an empty list of arguments. I like that in some ways,
but I don't like it in others. I've come down on the side of keeping its
invariant (it always takes only one scalar as an object) pure for now. If I
change it to take a list of updates, that might be the right time to reconsider
this.</p>

<p>What I notice in the code as it stands right now is that the individual
variables <code>$pe_update</code> and <code>$cash_yield_update</code> are
synthetic variables. They only exist to support the code as written; they're
not necessary for the algorithm. If I were to modify this code but only this code, I'd really rather write:</p>

<pre><code>{
    ADD_TXN_WITH( $self, analyze_pe,         $stock, $stock_txn    );
    ADD_TXN_WITH( $self, analyze_cash_yield, $stock, $analysis_txn );
}</code></pre>

<p>... though that syntax doesn't thrill me either. The clearest possibility I
see right now is:</p>

<pre><code>{
    $stock_txn-&gt;add(    SKIP unless $self-&gt;analyze_pe( $stock )         );
    $analysis_txn-&gt;add( SKIP unless $self-&gt;analyze_cash_yield( $stock ) );
}</code></pre>

<p>... where <code>SKIP</code> does some magic to move to the next statement,
not the next loop iteration. (I have some ideas how to write XS to make this
work, but that creepy yak needs a shave and some mouthwash.)</p>

<p>The second best option right now is adding a function or method as
indirection to encapsulate the synthetic code. I'd rather avoid synthetic code,
but at least it reduces the possibility of copy and paste bugs.</p>

<p>For now, with only two steps in this analysis, I'm leaving it as it is. Two
repetitions of something this similar set off my refactoring alarm, but I
resist the urge for refactorings this small until I see three instances of
near-duplicate code.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/02/03/a-practical-use-for-macros-in-perl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Decades-Old Technique to Improve Programming Languages</title>
		<link>http://www.modernperlbooks.com/mt/2012/01/a-decades-old-technique-to-improve-programming-languages.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/01/a-decades-old-technique-to-improve-programming-languages.html#comments</comments>
		<pubDate>Mon, 23 Jan 2012 20:22:23 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=444eb064a286b9c0c7a44d340e73f101</guid>
		<description><![CDATA[I promised in Testing Your Templates to explain how to solve the problem of the divergence between testable, debuggable code in your host language and a big wad of logic in a template language. This problem is an example of...]]></description>
			<content:encoded><![CDATA[
        <p>I promised in <a
href="http://www.modernperlbooks.com/mt/2012/01/testing-your-templates-and-why-it-doesnt-always-work.html">Testing
Your Templates</a> to explain how to solve the problem of the divergence
between testable, debuggable code in your host language and a big wad of logic
in a template language.</p>

<p>This problem is an example of the pattern of Why Writing Your Own DSL is
More Difficult Than You Think. Certainly Template Toolkit is among the better
templating systems (I've written a couple myself), but it exhibits problems
endemic to the process. (Then again, so does PHP. Now multiply that by the fact
that some people use templating systems <em>written in PHP</em> and if you have
to lie down for a while before the feeling passes, please accept my
apologies.)</p>

<p>The semantics of Template Toolkit are great, when they work, but then
everything's great when it works the way you expect. Robust software handles
the cases you don't expect with aplomb, or at least without a boom.</p>

<p>A simple workaround for Template Toolkit is to avoid the fallback from potential method lookup to keyed hash access when dealing with an object. In other words, if <code>$blessed_hash-&gt;do_something()</code> fails, try <code>$blessed_hash-&gt;{do_something}</code>.</p>

<p>... except that that doesn't work when you want to call virtual methods on
unblessed references, such as calling methods on arrays or hashes.</p>

<p>Another option is to change the syntax such that calling a method is visibly different from accessing a member of an aggregate. Perl 5 does this. It works pretty well, in the sense that if you use the right operator (access element versus invoke method), you've expressed your intent in a visually unambiguous fashion).</p>

<p>... except that people complain about the Perl 5 dereferencing arrow quite a
bit. (Okay, you don't <em>need</em> an arrow to do this; as the <a
href="http://onyxneon.com/books/modern_perl/index.html">Modern Perl book</a>
explains, the postfix indexed access or postfix keyed operators of
<code>{}</code> and <code>[]</code> determine the type of operation
effectively.)</p>

<p>... and except that one of the design goals of Template Toolkit was to be
robust in the face of changing values provided to the template, such that it
provides a loosely coupled interface for the data it expects. That's a fine
goal, but it isn't free.</p>

<p>Here's the thing, though. The last time I looked, Template Toolkit compiles
templates into Perl 5 code as an optimization. (The last template system I
wrote did the same thing, but not as well. We should have used TT, but in our
defense, TT didn't exist then.) This transliteration/compilation stage must be
very, very cautious to allow standard Perl debugging and introspection tools to
treat this generated code correctly. That is to say, I don't want to debug a
big wad of generated code. I want to debug the code I actually wrote.</p>

<p>As usual, the solution is another layer of abstraction.</p>

<p>Perl 5 exists in two forms. The first is the source code you and I write.
The second is the optree which the Perl 5 VM executes. There's nothing in
between. You have one or the other. When your code runs, you have the optree,
and the optree has references to the relevant location in the source code it
came from, but the correspondence is often less useful than you might like.</p>

<p>While the generated code from Template Toolkit could include the correct
file and line positions from templates, that's again less useful than you might
like. (It's useful, but it doesn't solve every problem.)</p>

<p>If Perl 5 had instead an intermediate form separate from raw code and raw
optrees, something more suitable to introspection and manipulation, we could
produce tools which worked with this intermediate form to improve debugging,
introspection, and better code generation.</p>

<p>We could even <em>inject</em> new code to add features (fall back to
attribute access; prevent the fallback to attribute access) to code, even
within lexical scopes. That is to say, we could manipulate how libraries behave
from the outside in, and ensure that our changes would not leak out from our
desired scopes.</p>

<p>It's certainly possible to replace the Perl 5 opcodes yourself, if you're
comfortable reading Perl 5 source code, writing XS, relying on black magic, and
dealing with strange issues of thread safety and manipulating global or at
least interpreter-global values in a lexical fashion (while dealing with the
fact that <code>use</code> is recursive in a sense)&mdash;but isn't Perl about
<em>not</em> making people write C to do interesting things?</p>

<p>Certainly this isn't a technique you'd use every day, and it's not obviously
a way to make Perl 5 run faster (though many optimizations become much easier),
but the possibility for better abstraction and extension and correctness has
much to recommend it.</p>

<p>And, yes, Lisp demonstrated this idea <em>ages</em> ago.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/01/23/a-decades-old-technique-to-improve-programming-languages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>If We Could Resolve Predicates at Compile Time</title>
		<link>http://www.modernperlbooks.com/mt/2011/12/if-we-could-resolve-predicates-at-compile-time.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/12/if-we-could-resolve-predicates-at-compile-time.html#comments</comments>
		<pubDate>Mon, 12 Dec 2011 18:27:07 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[typing]]></category>
		<category><![CDATA[webprogramming]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=4e36ac66b0108e9ced4978e017bbe995</guid>
		<description><![CDATA[The Catalyst web framework uses Perl 5 function attributes effectively&#38;mdash;I've seen few more effective uses of attributes. Any modern web framework has to deal with the idea of routes and request routing somehow. Given a request path (such as /stocks/AA/view_analysis),...]]></description>
			<content:encoded><![CDATA[
        <p>The <a href="http://catalystframework.org/">Catalyst web framework</a> uses
Perl 5 <a
href="http://perldoc.perl.org/perlsub.html#Subroutine-Attributes">function
attributes</a> effectively&mdash;I've seen few more effective uses of
attributes.</p>

<p>Any modern web framework has to deal with the idea of routes and request
routing somehow. Given a request path (such as <em>/stocks/AA/view_analysis</em>),
how does your application know what to do?</p>

<p>Catalyst solves this elegantly with a feature known as chained actions.
Controller methods can consume zero or more parts of the path but, when
explicitly chained, can combine. Consider the example request path. The
controller is <em>Stocks.pm</em>. The second component of the path
(<em>/AA</em>) is the identifier for a stock (<a
href="http://www.alcoa.com/global/en/home.asp">Alcoa</a>, to be specific. I'm
neither long nor short on Alcoa itself, though I probably own some shares as
part of a fund somewhere.) The final component of the path,
<em>/view_analysis</em>, is an action&mdash;a verb representing an action the
controller should take on the object representing Alcoa in the system.</p>

<p>You can probably start to see the idea of the chain right away.</p>

<p>The Stock controller has a controller method called <c>get_stock</c> which
grabs the stock symbol from the request path, looks it up in the database, and
stores the object representing that stock for further processing. If no such
symbol exists, it throws an exception.</p>

<p>The <code>view_analysis</code> method chains off of the <c>get_stock</c>
method such that Catalyst will only dispatch to <code>view_analysis</code> when
it's already successfully dispatched to <c>get_stock</c>. Unless you write a
custom dispatch system which bypasses the dispatch rules, users will never be
able to call <code>view_analysis</code> without a valid stock object
available.</p>

<p>(Further, these methods are part of a chain which requires that users have
successfully logged into the system; they chain off of a user authentication
system.)</p>

<p>In code terms, the relevant attributes look something like:</p>

<pre><code>sub authorized :Chained('/login/required') :PathPart('stocks') :CaptureArgs(0);

sub get_stock :Chained('authorized') :PathPart('') :CaptureArgs(1);

sub view_analysis :Chained('get_stock') :PathPart('view_analysis') :Args(0);</code></pre>

<p>The <code>:Chained</code> attribute is most relevant here.
<code>:PathPart</code> governs how Catalyst's dispatcher makes each method
visible to user requests (<code>get_stock</code> doesn't consume a part of the
path on its own, while <code>authorized</code> consumes the name of the
controller and <code>view_analysis</code> consumes its own name).
<code>:CaptureArgs</code> and <code>:Args</code> control how many other pieces
of the path the methods consume; in the case of <code>get_stock</code>, it's
the single path element between <code>/stocks</code> and any subsequent chained
actions&mdash;in this case, <code>/AA</code>. As <code>view_analysis</code> is
the end point of a chain, you use <code>:Args</code> instead of
<code>:CaptureArgs</code>.</p>

<p>With that all explained, request method chaining is fantastic. I can reuse
<code>get_stock()</code> for other request methods and get all of its benefits,
including the fact that only authorized users can even reach this point.</p>

<p>Yet I want to <em>prove</em> these characteristics of my application.</p>

<p>I want to prove these features so definitively that I don't want to write
tests for them. I want my program to fail to <em>compile</em> if these
characteristics are untrue.</p>

<p>I see chaining from <code>get_stock()</code> as supplying an invariant
precondition to <code>view_analysis()</code> such that it proves, to my
satisfaction, that I can always rely on a valid stock object being available
within the analysis method. Always. Similarly, I can always rely on a valid
user being available within both methods. Always always.</p>

<p>The problem comes in that it's easy to make a typo in the name of a chain or
a method, or to use <code>:CaptureArgs</code> instead of <code>:Args</code> or
vice versa.</p>

<p>Here's the thing: all of this metadata is metadata. All of this information
is available at compile time, before Perl has to execute anything.</p>

<p>If I had a really good and extensible type system in Perl 5, I could write a
couple of pieces of predicate logic to say that every chained method should be
a starting point or have a valid predecessor. These are trivial properties of
my program (no matter how large it gets) and they're resolvable with the
information available at the point of compilation. Even with complex controller
construction through the use of roles and parametric roles, this information is
available.</p>

<p>I know how to emulate this behavior by injecting some sort of
<code>CHECK</code> block into the code and schlepping through the symbol table
and inspecting attributes myself, but that's emulating a useful feature we
could exploit in a lot of ways.</p>

<p>Forget the talk about making Perl into Java or C++ by adding a silly
manifest static type system. We could find and fix real errors in
logic&mdash;trivial errors, trivially discoverable&mdash;if we had an
extensible type system which let us define our own simple predicates.</p>

<p>(Implementing such is left as an exercise for a small army of readers cloned
from a very small army of brilliant p5p hackers with copious spare time and a
habit of reading ACM papers before breakfast.)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/12/12/if-we-could-resolve-predicates-at-compile-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving Problems or Absorbing Design Patterns</title>
		<link>http://www.modernperlbooks.com/mt/2011/11/solving-problems-or-absorbing-design-patterns.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/11/solving-problems-or-absorbing-design-patterns.html#comments</comments>
		<pubDate>Sat, 26 Nov 2011 19:29:19 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[perl6]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=2f08ecc187cd5d72c80f436d134e98b1</guid>
		<description><![CDATA[At the end of January I decided that Perl 6 is currently impractical for my purposes, but other people have different ideas. In any serious discussion of Perl 6, you'll find people claiming that Perl 6 is already usable. Discovering...]]></description>
			<content:encoded><![CDATA[
        <p>At the end of January <a href="http://www.modernperlbooks.com/mt/2011/08/why-my-side-project-doesnt-use-perl-6.html">I decided that Perl 6 is currently impractical for my purposes</a>, but other people have different ideas. In any serious discussion of Perl 6, you'll find <a href="http://perlmonks.org/?node_id=939875">people claiming that Perl 6 is already usable</a>.</p>

<p>Discovering <a
href="http://www.modernperlbooks.com/mt/2011/10/in-search-of-minimum-viable-utility.html">the
minimum viable utility of a programming language</a> is a difficult exercise.
Certainly in 1994 few people would have expected that the obvious successor to
Perl 4 would eventually need multi-megabytes of extensions to add a full object
system rivaling CLOS plus Smalltalk, an asynchronous event system, a
high-powered object-relational mapper with pervasive laziness, and an
abstraction mechanism for HTTP? Yet that's the state of the art in Perl in
2011, and we're all the better for it.</p>

<p>If you read carefully between the lines of my criticism of the current state
of every Perl 6 implementation I've used as well as what the people who claim
that "Perl 6 is usable right now" write, you may find that we approach the
problems we're trying to solve from two different angles. We even
<em>agree</em> on one of those vectors.</p>

<p>When someone like <a href="http://moritz.faui2k3.org/">Moritz Lenz</a>
writes "You can use Rakudo or Niecza for real programs now!", I think it's fair
to rephrase that as "Any of the leading Perl 6 implementations implements
enough structure of a complete and useful programming language that you can
implement your own code."</p>

<p>I can agree with this sentiment. I even go a step further; I don't mean to
water down his assertion or to put words in his mouth. If you analyze Perl 6
right now in terms of the <a href="http://dev.perl.org/perl6/rfc/">Perl 6
RFCs</a>, it's clear that Perl 6 even as currently implemented has advantages
over Perl 5 when you compare features on a matrix.</p>

<p>(I've since come to believe that <a
href="http://www.modernperlbooks.com/mt/2011/11/promoting-perls-features-versus-benefits.html">you're
dooming yourself to potential technical excellence and popular obscurity by
focusing on features instead of Getting Stuff Done</a>.)</p>

<p>To rephrase, Perl 6 may certainly be a better programming language than Perl
5 in that Perl 6 includes features Perl 5 should have had years ago. If design
patterns are signposts of missing language features, Perl 6 is the <a
href="http://c2.com/cgi/wiki?ChristopherAlexander">Christopher Alexander</a> of
programming.</p>

<p>If that's sufficient for your purposes, great. (You still have to deal with
performance issues and regressions, and licensing concerns with the Mono
dependency of Niecza (Niecza fans, be honest. How is my business supposed to
pay Novell anymore for indemnification per their patent licensing arrangement
with Microsoft&mdash;you remember, the Microsoft that sued TomTom for patent
infringement?), and the schism between Parrot and Rakudo on the Rakudo side, as
well as the history of Rakudo undergoing lengthy and repeated and
compatibility-busting rewrites of core components, but after eleven and a half
years, you ought to know you're an early adopter by now.  (Rakudo fans, be
honest. How long after nom became the main development branch did it take to
get all of the Panda modules passing tests again? Oh, they're still not?
QED.)</p>

<p>The other vector from which to approach problem solving in Perl says
something like "You know, if I'm already leaning heavily on the CPAN to
download Plack and an IMAP server and an OAuth implementation and AnyEvent and
several testing distributions, Moose really isn't that big a deal anymore." In
other words, maybe it is rather silly that in 2011 Perl 5 still doesn't have
much of an object system in the core and that it could really use real function
signatures, but the Perl community is awfully good at making the important
stuff on the CPAN just work, and Perl 5 without the CPAN is pretty anemic for
solving big important problems anyway, so grab perlbrew and fire up cpanm and
after you've finished your cup of tea, you're all set anyway.</p>

<p>The Python community has dealt with the same schism between Python 2.x and
Python 3.x, where Python 3 is arguably a better <em>language</em>, but only
superficial polyglot magpies and Usenet personas care solely and forever about
language qua language, and everyone else eventually needs to use a library or a
framework or a tool written by someone else.</p>

<p>I thought I wanted a better language to solve my problems, but as it turns
out, right now I can't have both, and I want to solve my problems more than I
want a better language. A good enough language which lets me solve my problems
is better than a great language in which I'm practically unproductive.</p>

<p>This is one of the few times when I agree both with the backwards
compatibility people <em>and</em> Python programmers. Mark your calendar.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/11/26/solving-problems-or-absorbing-design-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

