Best things in life come in threes

2009 November 8
by draegtun

Following on from my last post it seems I have also been waiting for a kind of virtual conjunction between Perl 5.10.1, Parrot 1.0 & Padre being a year old.

Perl 5.10.1

Currently I run 5.8.8 in production on all servers that I manage. I do have Perl 5.10.0 running locally on my Mac but only for playing with.

So first step is to load Perl 5.10.1 on my Mac (Tiger) alongside my other Perl’s and then start testing & with the plan to roll it out to replace 5.8.8 in the not too distant future.

These are my steps to load 5.10.1 locally so that it doesn’t conflict with any other Perl I have here:

  • Download & unpack Perl source code in my normal user login
  • perl Configure -de -Dusethreads -Dprefix=~/local/Perl/perl-5.10.1/
  • gmake
  • gmake test
  • gmake install-all

I now have Perl 5.10.1 running out of my $HOME directory.

This all worked fine except the default location of .cpan directory was in $HOME (~/.cpan). This could clash with other locally installed Perl if nothing is done so I amended everything in cpan shell to use ~/local/Perl/perl-5.10.1/.cpan instead (I did this using “o conf”).

I then quickly blasted my new local Perl 5.10.1 with a few CPAN modules which included:

  • Moose
  • MooseX::Declare
  • autobox::Core
  • DateTime
  • XML::LibXML
  • Devel::REPL

All modules I selected installed without a single hitch. CPAN comes up trumps again!

Devel::REPL was of great interest to me because when I last tried to install this on 5.8.8 & 5.10.0 I did have some problems.

This time it installed & worked wonderfully. Only slight issue was there was no command line history? (ie. readline). This was easily resolved by loading Bundle::CPAN (which also gave cpan shell history as well!)

Padre

Normally I don’t compile Perl with threads. However I needed it for Padre, which is something I forgot about when I last tried installing Padre on my local 5.10.0 :(

I installed the following CPAN modules into my new Perl 5.10.1:

  • Alien::wxWidgets
  • Wx
  • Padre

All compiled & installed seamlessly. On starting Padre I got a nice pretty butterfly splash screen but then unfortunately it crashed :(

As with most things in life if you not starting off with a clean slate then it may cause problems. I had some residue stuff from previous attempt that was part of the problem.

Two things were needed resolve this stumbling block:

  • Remove WxWidget which was installed via MacPorts (sudo port deactivate wxWidgets)
  • Make sure new Perl 5.10.1 was first Perl in $PATH env variable. Because even though I was running 5.10.1 CPAN shell the Wx module seemed fixated on picking up Alien::wxWidgets from the first Perl it could get its hands on :-P

After this reinstalling the Wx & Padre modules gave me a fully functional Padre.

Parrot 1.0 / Rakudo / Perl6

I was now using Padre 0.48 to edit & run my Perl 5.10.1 code. Want I wanted now was to add Perl6 into the mix.

For this I just followed the instructions from Rakudo site and installed it in my local user dir with no hitch at all.

Next in Perl 5.10.1 I installed the Padre::Plugin::Perl6 to make Padre Perl6 aware. My first bit of Perl6 code ran from Padre & command line perfectly (don’t forget to add your rakudo path to $PATH env):

use v6;

for 1..10 { .say }

class Dog {
    method bark { "woof" }
}

my Dog $rover .= new;
my $spot = Dog.new;

say $rover.bark;
say $spot.bark;

 

So where do I stand with Padre? Well I do love my Textmate so it is going to be hard to tug me away from it.

But I love the idea of an editor being hosted and extensible in Perl. So come my next round of free time I may find the tugging from Padre just to strong to resist ;-)

/I3az/

Patience is a virtue

2009 October 31
by draegtun

For about a year I’ve put off replacing my Apple iMac with a Mac Pro until Snow Leopard arrived.

But thats nothing because I’ve been hanging on to my old, tired and very battered Sony Ericsson mobile phone while I’ve been waiting for the iPhone to eventually come to my mobile phone network

Waiting looks to have paid off because the new 27inch iMac with the Nehalem processors certainly look sweet. I even got to play with magic mouse at an Apple store the other day and have to say first impressions were very nice.

So new iMac will be a nice Xmas pressie :)

The iPhone is a few months off yet but I can hold on a bit longer :(

The temptation to buy a Google Android phone was strong though. It came close especially when Google announced that Perl was available for it.

Gosh having Perl on a “mobile” device brings back memories. I had Perl running on my Psion Revo PDA back in the day.

Unfortunately no Perl on the iPhone thus far… unless its jail broken!

Still perusing the iTunes App Store does show up a few things Perl. O’Reilly have “ported” quite a few of their books to the store.

Amazingly i am still an app virgin on my iPod Touch! So I thought I’d give it a go and purchase Perl Pocket Reference app.

I can’t say its this e-book is going to set my world alight but for £1.79 I couldn’t really go wrong and you will never know when it will come in handy.

/I3az/

Blogging Milestone

2009 October 22
by draegtun

When I started this blog my “ideal” scenario was to post weekly. However my “pragmatic” operand was to at least post every month.

So with a broad grin of achievement I see that yesterday I passed the milestone of posting a blog entry on every single month for a whole year!

Always nice to give one self a little pat on the back from time to time. But I also have to thank Perl Iron Man for providing the required stimulus at the right moment :)

I’ll try not to rest on my laurels so I will see if I can raise the gears up a few notches over next few months (surely I can become more than a paper man!).

Before I go a couple of recent blogging changes that I can’t take any credit for whatsoever are:

  • WordPress syntax highlighting as changed again. Perl code is now is a more subtle nicer looking font
  • iPhone / iPod Touch users will now see a tailored rendering of this site. Looks very snazzy.

/I3az/

Stackoverflow.com and Perl

2009 October 12
by draegtun

A couple of weeks ago I was pleasantly surprised by being 10th person to receive a Perl badge on Stackoverflow

so-badge

Slipping in at number 10 with such other celebrated Perl names if indeed an honour. *blush*

Of course none of this will mean a jot if you’ve never heard of Stackoverflow.com!

Its a programming language question and answer site started by Joel Spolsky (of Joel on Software fame) and Jeff Atwood (of Coding Horror fame).

Its very similar in vein to Perlmonks except its for all programming languages and not just Perl and its also Q&A only. So no mediations, epiphanies or wandering off topic ;-)

You will need an OpenID account to start but once past that you will find the site easy to use. Just start asking or answering questions. You get up or down voted depending on the quality of your question/answer.

I do feel the site is more approachable than Perlmonks especially for beginners. Its also a good place to start when looking for a clear answer to a specific question.

So what’s in it for me?

Well you can just view it as a game or challenge. Perhaps even treat it as a ladder to Rock and Roll stardom! Certainly nothing wrong with bit of ego inflating now and then ;-)

Or you can view it as a philanthropic pursuit by spreading things you learnt with others.

However the thing I get most from it all is that I’m continuing to learn new things. And in most cases its from my own answers! You can really enhance your Perl foo and improve your Perl memory muscles when trying to answer a question.

Disclaimer: It can get addictive. If you have a procrastinating nature then please avoid during the working day ;-)

So what’s in it for all of us?

Stackoverflow continues to grow. More and more programmers are getting sucked into it. Some of these are beginners or language toe dippers so the presence of good Perl questions & answers may benefit the Perl community in many different ways.

Here’s a good place to start: Perl tagged questions.

/I3az/

Simple as text

2009 October 3
by draegtun

Well I’ve gone thru and amended all my previous posted code to use the new
Perl syntax highlighting. Yawn :(

My grandmother always told me I shouldn’t learn a craft or trade which relied on electricity ;-)

I think my sage advise to my future grandchildren will be:

Don’t use anything which cannot be easily munged with favourite programming language!

/I3az/

PS. I have just now noticed on CPAN some WordPress modules:

* WordPress
* WordPress::API

I’ll have to give these a closer look next time round ;-)

blog syntax highlighting

2009 September 28
tags:
by draegtun

First the bad news. At some point last week all code previously posted here suddenly had all its comments converted into upper case :(

Now the good news. While looking into why WordPress syntax highlighter was suddenly doing this I re-tested to see if Perl had been added and lo and behold it had!

This is how a previous code looked using “ruby”:

# sourcecode lang="ruby"
{
    package Anonyject;
    use MooseX::SingletonMethod;
}

my @dingfirsts;
for my $line ( 1..10 ) {
    push @dingfirsts, Anonyject->new->add_singleton_methods(
        ding => sub { 'ding' x $line },
        dong => sub { 'dong' x $line },
        line => sub { $line },
    )
}

for (@dingfirsts) {
    say "First ", $_->ding, " on line ", $_->line;
}

Now Perl works!:

# sourcecode lang="perl"
{
    package Anonyject;
    use MooseX::SingletonMethod;
}

my @dingfirsts;
for my $line ( 1..10 ) {
    push @dingfirsts, Anonyject->new->add_singleton_methods(
        ding => sub { 'ding' x $line },
        dong => sub { 'dong' x $line },
        line => sub { $line },
    )
}

for (@dingfirsts) {
    say "First ", $_->ding, " on line ", $_->line;
}

WordPress must have updated this plugin last week. Hopefully they’ll fix the comment issue soon ;-)

Anyway the Perl code is so much nicer. The Ruby sigil variables were in bold which wasn’t nice on the eye. I’ll be updating all my previous posts to now use Perl highlighting very shortly.

/I3az/

Easy Anonymous Objects

2009 September 16
tags:
by draegtun

On use Perl; the other day revdiablo asked whether there were Anonymous objects as easily as hashrefs? any where within Moose or sitting (hiding!) on CPAN.

Well the answers posted gave a yes for both Moose & CPAN.

Here is my twist on things using something already on CPAN which uses Moose and its Class::MOP foundations: MooseX::SingletonMethod.

With this we can easily create anonymous singleton objects like so:

{
    package Anonyject;
    use MooseX::SingletonMethod;
}

my @dingfirsts;
for my $line ( 1..10 ) {
    push @dingfirsts, Anonyject->new->add_singleton_methods(
        ding => sub { 'ding' x $line },
        dong => sub { 'dong' x $line },
        line => sub { $line },
    )
}

for (@dingfirsts) {
    say "First ", $_->ding, " on line ", $_->line;
}

We can show that each of these objects created have unique anonymous classes using Moose introspection:

for (@dingfirsts) {
    say $_->line, ': ', ( $_->meta->class_precedence_list )[0];
}

# outputs
# => 1: Class::MOP::Class::__ANON__::SERIAL::2
# => 2: Class::MOP::Class::__ANON__::SERIAL::3
# => 3: Class::MOP::Class::__ANON__::SERIAL::4
# => 4: Class::MOP::Class::__ANON__::SERIAL::5
# => 5: Class::MOP::Class::__ANON__::SERIAL::6
# => 6: Class::MOP::Class::__ANON__::SERIAL::7
# => 7: Class::MOP::Class::__ANON__::SERIAL::8
# => 8: Class::MOP::Class::__ANON__::SERIAL::9
# => 9: Class::MOP::Class::__ANON__::SERIAL::10
# => 10: Class::MOP::Class::__ANON__::SERIAL::11

The rest of the class chain upwards for each of these objects is:
Anonyject >> Class::MOP::Class::__ANON__::SERIAL::1 >> Moose::Object

So you can add methods or attributes to Anonyject class and they will be available to all the anonymous objects created.

NB. Class::MOP::Class::__ANON__::SERIAL::1 is where the MooseX::Singleton methods live.

So for more proof in the singleton pudding:

my $obj1 = Anonyject->new->add_singleton_methods(
    ding => sub { "wing" },
    dong => sub { "wong" },
    line => sub { 23_939 },
);

my $obj2 = Anonyject->new->add_singleton_methods(
    something => sub { "else" },
);

say $obj1->ding;      # Says "wing"
say $obj2->something; # Says "else"

say $obj1->something; # Should break and now does
say $obj1->broken;    # Breaks properly
say $obj2->dong;      # And also breaks properly

And all these objects are easily extensible:

# add dingdong just to $obj2
$obj2->meta->add_method( dingdong => sub { 'dingdong!' } );
say $obj2->dingdong;   # "dingdong!"

# add bang to all anonymous Anonyject objects
Anonyject->meta->add_method(
    bang => sub { 'bang ' . ( $_[0]->meta->class_precedence_list )[0] }
);
say $obj1->bang;       # "bang Class::MOP::Class::__ANON__::SERIAL::12"
say $obj2->bang;       # "bang Class::MOP::Class::__ANON__::SERIAL::13"

/I3az/

Building a STS (Simple Template System)

2009 September 14
tags:
by draegtun

Marek Foss recently posted a Simple Template System in Perl article on his f055: lazy design & development blog.

This got my brain buzzing and had a few hours to kill. So I decided to stretch my Perl foo & memory to build a STS from scratch to pass the time.

Here was the first prototype:

#!/usr/local/bin/perl -T

use strict;
use warnings;
use CGI ();

sub transform {
    my ($template, $vars) = @_;
    eval {
        no warnings;
        $template =~ s/<!--(.*?)-->/$vars->{$1}/g;
    };
    return $template;
}

sub internal_template {
    my $tmpl;
    $tmpl.= $_ for <DATA>;
    return $tmpl;
}

print CGI::header( -type => 'text/html' );

print transform internal_template() => {
    sidebar => 'This is a menu',
    content => 'This is the main content block',
};

__DATA__
<html>
<head>
<title>Simple Template System</title>
</head>
<body>
<div class=“menu”>
<!--sidebar-->
</div>
<div class=“main”>
<!--content-->
</div>
</body>
<!--baz-->
</head>

I’m using a hashref to pass the template variables. This is more flexible and allows me to use just the one substitution to transform all the template placeholders:

$template =~ s/<!--(.*?)-->/$vars->{$1}/g;

The eval & “no warnings” around this cover issues like calling an unknown template variable (ie. undefined hash key). For eg. see <!–baz–> silently disappears from output.

I am also using an internal_template() where the template HTML follows the __DATA__ line. Nice for simple CGI scripts but nothing stopping us having external_template() either.

If you require more than one internal template then:

#!/usr/local/bin/perl -T

use strict;
use warnings;
use CGI ();

sub transform {
    my ($template, $vars) = @_;
    eval {
        no warnings;
        $template =~ s/<!--(.*?)-->/$vars->{$1}/g;
    };
    return $template;
}

sub internal_template {
    my $show = shift;
    my %tmpl;
    my $template_name = 'main';  # default (1st) template

    for my $line ( <DATA> ) {
        if ( $line =~ m/^\*\*\*\s(\S+)\s\*/ ) {
            $template_name = $1;
            next;
        }
        $tmpl{ $template_name }.= $line;
    }
    return exists $tmpl{ $show } ? $tmpl{ $show } : $tmpl{ main };
}

print CGI::header( -type => 'text/html' );

print transform internal_template() => {
    sidebar => 'This is a menu',
    content => 'This is the main content block',
};

__DATA__
<html>
<head>
<title>Simple Template System</title>
</head>
<body>
<div class=“menu”>
<!--sidebar-->
</div>
<div class=“main”>
<!--content-->
</div>
</body>
</head>
*** nomenu *************************************************************
<html>
<head>
<title>Simple Template System (nomenu)</title>
</head>
<body>
<div class=“main”>
<!--content-->
</div>
</body>
</head>

Now there is a separator between each template (*** template_name ***). internal_template() now takes an optional template name (internal_template(‘nomenu’) would produce the alternate template in above code).

So what would a STS need next?

Well having functions passed to the template that can be called could be handy. This can be achieved by preceding an additional text substitution in the transform() sub:

$template =~ s//@{[ $vars->{$1}->( split ',', $2) ]}/g;

This code picks up placeholders with parenthesises and passes the parameters given to the specified function name. The @{[ ... ]} does the extra bit of interpolation work needed for this to work.

Thus we can create function placeholders like this:

print transform internal_template('main') => {
    gbp       => sub { sprintf "£%.2f", $_[0] },
    li_helper => sub { map { qq{<li>$_</li>} } @_ },
};

using a template like this:
<p>Great British Pounds: <!--gbp(200)--></p>
<ul><!--li_helper(one,two,three)--></ul>

would produce the following:

<p>Great British Pounds: £200.00</p>
<ul><li>one</li> <li>two</li> <li>three</li></ul>

OK so far so good. But what if I wanted to call a Perl function without having to pre-define anything in script? Well we could precede the following substitution into transform() sub:

$template =~ s/<!--perl(.*?)-->/@{[ eval "$1" ]}/gs;

Which means you then could do something like this:
<p>Random number between 1 and 9: <!--perl int( rand(10) ) --></p>

Well this is all nice and dandy if all we want is the expression results returned. What if we wanted to use control statements that effect the output? ie. something like this in the template:

if ( int(rand(2)) ) {
    print '<ol>';
    for my $numb (1..5) {
        printf('<li>%d * 2 = %d</li>', $numb, $numb * 2);
    }
    print "</ol>\n";
}
else { print "</p>Nothing to show at this moment in time</p>" }

We’re starting to play with fire now! This can be achieved with a bit more control of the output stream so I created a process() subroutine to handle that.

Below is the full program with everything in bar the kitchen sink:

#!/usr/local/bin/perl -T

use strict;
use warnings;
use CGI ();

sub transform {
    my ($template, $vars) = @_;
    eval {
        no warnings;
        $template =~ s/<!--perl(.*?)-->/@{[ eval "$1" ]}/gs;
        $template =~ s/<!--(.*?)\((.*?)\)-->/@{[ $vars->{$1}->( split ',', $2) ]}/g;
        $template =~ s/<!--(.*?)-->/$vars->{$1}/g;
    };
    return $template;
}

sub process {
    my $tmpl = shift;
    my $vars = shift;
    my $buffer;

    my $start = qr{<\?perl>};
    my $end   = qr{</\?>};

    for (split /\n/, transform( $tmpl, $vars)) {
        if ( /$start/ .. /$end/ ) {
            if    ( /$start/ ) { $buffer = '' }
            elsif ( /$end/   ) {
                eval $buffer;
                $buffer = '';
            }
            else { $buffer.= $_ . "\n" }
            next;
        }
        print $_, "\n";
    }
}

sub internal_template {
    my $show = shift;
    my %tmpl;
    my $template_name = 'main';

    for my $line ( <DATA> ) {
        if ( $line =~ m/^\*\*\*\s(\S+)\s\*/ ) {
            $template_name = $1;
            next;
        }
        $tmpl{ $template_name }.= $line;
    }
    return exists $tmpl{ $show } ? $tmpl{ $show } : $tmpl{ main };
}

print CGI::header( -type => 'text/html' );

process internal_template('main') => {
    sidebar => 'This is a menu',
    content => 'This is the main content block',
    gbp     => sub { sprintf "£%.2f", $_[0] },
    li_helper => sub { map { qq{<li>$_</li>} } @_ },
};

__DATA__
<html>
<head>
<title>Simple Template System</title>
</head>
<body>
<div class=“menu”>
<!--sidebar-->
</div>
<div class=“main”>
<p>Great British Pounds: <!--gbp(200)--></p>
<ul><!--li_helper(one,two,three)--></ul>
<p>Random number between 1 and 9: <!--perl int( rand(10) ) --></p>
<?perl>
    if ( int(rand(2)) ) {
        print '<ol>';
        for my $numb (1..5) {
            printf('<li>%d * 2 = %d</li>', $numb, $numb * 2);
        }
        print "</ol>\n";
    }
    else { print "</p>Nothing to show at this moment in time</p>" }

</?>
<!--content-->
</div>
</body>
<!--baz-->
</head>

process() simply loops thru the fulfilled template printing out each line as it goes along except when hitting a <?perl> block which it evals instead.

Above isn’t perfect but it does exactly what it says on the tin. Well that is it use to before I bogged it down with features. I don’t think we can call it a Simple Template System anymore? How about “Super”? “Spectacular”? or even “Special”? Perhaps another word beginning with “S” maybe more appropriate ;-)

They say writing a template system is a rite of passage for every Perl programmer. Its been a while since I did my last one so perhaps its also some kind of recursive itch we have?

Anyway I’ll stop procrastinating and return to using Template Toolkit for my templating needs ;-)

/I3az/

A week is a long time in perlitics

2009 September 6
tags:
by draegtun

Well my extended bank holiday weekend break turned into to be a nice long week away in the New Forest. So that’s a whole week without computers, internet and Perl ;-)

So on my return its nice to see a bustling RSS feed of Perl posts! In fact in quantity the Ironman feed out did the Ruby Corner feed I also subscribe to. Looks like a very vibrant community to me.

And its not just quantity because there have been some colourful posts while I’ve been away!….

  • Moose certainly claimed most of the headlines over past week! Moose brings a lot of enjoyment and productivity to my Perl but I’m pragmatic enough to know its not a panacea for all solutions (though I am dreaming of that day!).
  • RedHat “drops” CPAN.pm from Perl on Fedora. A bit of unnecessary tap dancing going on with package naming methinks!
  • HTTP::Engine and PSGI. I have been playing with HTTP::Engine and had to overcome some stumbling blocks with streaming out dynamic data (that reminds me I need to do blog post on that!), so its going to be interesting to see what PSGI brings to the table.

    NB. Its also poignant to note that Pythonistas have recently expressed that WSGI isn’t necessary the definitive solution and have envious snake eyes on Ruby’s Rack.

  • So the Ironman badges are now available and I’m a…. Stone Man :(

    Well at least I was when I checked yesterday because looking at it today and I see I’m now a Paper Man! sob!? Hmmm… well hopefully things will change after I make this post!

So whats been missed that I can add to the news:

  • GitHub contest is over. Its not clear yet but Ultraist Perl entry appears to have came 6th (with score of 2475) and could be the highest dynamic language solution. Well done Ultraist
  • Perl jumps up two places on Tiobe index to #6 (swapping places with Python).

    NB. And this as nothing to do with this because cpan.org still shows same search figures. There have been some additions to cpantesters & perldoc sites which may have helped but I believe a lot of the difference can hopefully be attributed to Ironman and the resurgence in Perl blog posts. Well done everyone methinks!

/I3az/

PS. I’m not putting in Tiobe link…. I’m sure u can find it in Google quite easily ;-)

Something for the Bank Holiday weekend

2009 August 28
tags: ,
by draegtun

Well if you’ve got nothing to do this long bank holiday weekend (UK hols) then you could enter the GitHub Contest. You’ve got till noon Sunday PST to enter your solution ;-)

I’ve had this on my “interesting todo” list for a while now. Like a lot of things on that list which have deadlines they unfortunately tend get passed by :(

I’ve made a promise to stay away from computer this bank holiday weekend. Shame because data munging with Perl is something I do enjoy doing.

There have been a few Perl solutions entered:

John Resig is a cheeky top score ditty ;-)

Ultraist is currently 8th on the leaderboard with a much more complex solution.

I think this is currently the highest Perl entry…. so good luck Ultraist and all other Perl entries.

/I3az/