Recently in Perl Category

| 3 Comments

Since it's Sunday, I had a couple extra hours to spare in the evening, so I decided to play around some more with Moose.

More specifically I've seen MooseX::Declare mentioned on several occasions so why not give it a go myself.

This module provides a fancier declarative syntax you can use to define objects much more in the tradition of other so-called 'real' OOP languages. It also automatically includes MooseX::Method::Signatures, which means I can also use method declarations with type constraints to my heart's delight.

Also within the method declarations you get the good old $self as a freebie, meaning you don't always have to remember to use the my $self = shift statement. This makes the whole method declaration syntax cleaner and more elegant.

So having said all that here follows my simple example in which I'm able to try out some of the interesting deals on offer.

use MooseX::Declare;
use feature qw(say);

class Person {
    has 'age' => ( isa => 'Num', is => 'rw', default => 0 );
    has 'max_age' => ( isa => 'Num', is => 'rw', default => 75 );

    method get_older (Int $years_to_add = 1 where { $_ > 0 }) {
        $self->age( $self->age + $years_to_add ) if $self->is_alive;
    }

    method is_alive {
        return $self->age < $self->max_age;
    }

    method speak {
        say $self->is_alive ? "I'm alive!" : "I've kicked the bucket!";
    }
}

So let's see how good I've coded this, create a Moosified Person object and see if it all works.

my $x = Person->new( max_age => 35 );

while ($x->is_alive) {
    $x->get_older( 5 );
    $x->speak;
}

When I ran the program, it results in the following not so amazing output:

I'm alive!
I'm alive!
I'm alive!
I'm alive!
I'm alive!
I'm alive!
I've kicked the bucket!

I guess it works good, pretty darn good, will have to investigate this interesting functionality in more detail another day.

| 6 Comments

Whenever starting another Perl project, the very first command you should run better be the following:

$ module-starter --module=My::Module --author="[your-name]" \ 
                 --email=[your-email] --builder=Module::Install

This provides the developer with a basic environment for writing solid Perl code, e.g. a new directory called My-Module with all the good stuff ready for use:

MANIFEST
README
ignore.txt
Makefile.PL
Changes
lib/My/Module.pm
t/pod-coverage.t
t/pod.t
t/00-load.t
t/boilerplate.t
t/manifest.t

After that it's the following, and off you go.

perl Makefile.PL
make
make test
make install

Life couldn't be easier could it?

| 4 Comments

These days it is not very often that a new and exciting Perl book comes along. That's why I was very excited when my Amazon.co.uk box arrived by post the other day.

I gleefully ripped the cardboard box open and held in my very own hands the recently released Effective Perl Programming, 2nd edition. Twice the thickness of the first edition and jam-packed with even more useful information.

This is a fantastic read which covers just about every aspect of Perl needed to program like the pros. Myself having had quite some experience with Perl was pleasantly surprised to learn new and interesting tidbits and other gems of information. Since having already read the book from cover to cover a couple times, I now keep it close at hand for reference purposes.

This wonderful book can be useful for beginners although it's pretty detailed and technical at times, but it's real use I believe is for experienced folks like myself who want to refresh their memories, extend their horizons, and recharge their enthusiasm for exploring new and possibly dangerous territories.

Here's an example of one of those one-liner gems, see if you can figure out what it does:

@a[ map { $_ * 2 + 1, $_ * 2 } 0 .. ( $#a / 2 ) ] = @a

From Chapter 2, Item 17 we find the following quote which appropriately summarizes one of the important philosophies: Perl is a "human" language in that it has a context-dependent syntax.

Finally, here are some other interesting places you might want to explore:

I can recommend you get the book also. Have fun.

| 3 Comments

I really like programming languages that allow you to think less without compromising the quality of your coding practices. Take for instance the new smart match operator '~~' which was introduced in the latest Perl releases.

if ( '123.0' ~~ 123 ) { ... } # String and number: TRUE

You don't have to keep trying to remember if a given scalar is a string or a number or 'numish' (both), sometimes wrongly using the standard operators ( eq, ne, lt, ==, >= ) in the wrong places causing bugs which are hard to track down.

Don't forget to enable this functionality by including the following in your code:

use 5.010;

Or you can enable the feature by calling Perl with the '-E' option at the command line.

| 0 Comments

Read this from beginning to end, and you then tell me with a straight face that it hasn't completely changed your life.

I believe it is high time that we stop dilly-dallying around, that we face the future for what it is, for what is was meant to be, and take the challenge.

for 0..3 -> $even, $odd {
    say "Even: $even \t Odd: $odd";
}

An appropriate theme song could be "Start of Something Beautiful" by Procupine Tree (which just happened to be playing on RadioParadise twice while reading and then re-reading the link above on alternating even and odd days).

| 0 Comments

Going to attend the 7th Dutch Perl Workshop tomorrow in Arnhem.

Cannot wait to get up bright and early for a fun and relaxing day dedicated to the fascinating world of Perl. Last year was a blast and with lots of interesting talks I look forward to the trip.

During the ninety minute drive east, I'm going to crank up my latest Porcupine Tree CD and prepare myself for the busy day of mental gymnastics.

| 0 Comments

Sometimes after a long and weary day at work you just do not feel like making any comments.

@no_comments = grep {!/^#/} @blahblahblah;

| 0 Comments

So this evening I happened to find out about autodie, thanks to the latest entry in the Modern Perl Books blog by chromatic. Cool stuff.

So I had to run home right away and try it myself, and it works! The following simple snippet:

#!/usr/bin/perl

use strict;
use warnings;

use autodie;
open (my $fh, "<", 'this-file-does-not-exist');
...

generates the following error message:

Can't open 'this-code-does-not-exist' for reading: 'No such file or directory' at x.pl line 8.

No need to waste all that time trying to remember where to stick all those die() statements all over the place (do I use || or do I use or?). So from now on I'll be using autodie just for fun and for work and for play.

Check out Modern::Perl for yourself.

| 1 Comment

All those weird Dutch characters were messing me up, and my Perl code was generating all kinds of cryptic errors, like: Malformed UTF-8 character, Wide character in print, etc.

You see, buried deep in the Perl innards somewhere, something was choking bad with such double dotted characters like ë, ö, etc.

I struggled with a number of my own home-grown solutions, but they didn't work well with all possible situations.

Finally in desperation, while perusing through one of my favorite recluses for inspiration, the good old CPAN, I happened to spy the Encode module.

A little bell rang in my head, and I knew I was in the right place. Getting warm, getting warmer, warmer, boiling, boiling hot ... bingo.

$text = Encode::decode('iso-8859-1', $text);

That's the simple and basic little statement that saved me and made my day. What could possibly be easier than that, and why was it so hard for me to find?

Maybe in the future I should visit CPAN more often and earlier, and not think so much of myself. As if I can always solve these grueling problems on my own.

I'm a pretty smart guy, but a little assistance from my Perl friends is always a welcome helping hand.

| 3 Comments

Being the hard-core developer type person that I am, every couple of years or so I like to take up a new programming language. This activity provides me with new insights into the wonderful world of programming, seeing how other people tackle interesting problems in different ways.

So last month I picked up a copy of Programming in Lua, and boy has it been a fascinating read. I can definitely recommend purchasing a copy of this book to add to your arsenal of programming literature.

Since my favorite programming language is Perl, each new book I study makes me rethink and compare things about other programming language with Perl (and its potential limitations). This is what I have been doing with Lua.

Two interesting features of Lua which would be great if Perl could do something similar are: "tail-call elimination" and "coroutines".

Tail-call elimination

Basically a tail-call is a goto in disguise. Place as the last statement in a function a return g(x) and you've got a tail-call:

function f(x) return g(x) end

Since the function f(x) has nothing else to do, it doesn't make sense having it wait around until the tail-call returns, using up unused resources like the stack. Might as well avoid using the extra stack space, making it possible to call an unlimited number of nested calls without worrying about the stack overflowing. The following example function can be called forever and the stack will never run out.

function foo(n)
    if n > 0 then return foo(n -1) end
end

A useful example application mentioned in the book, would be traversing a maze with the tail call providing a simple state machine describing going from one cell to the other. Each step goes north, south, east or west into the adjacent room, the exit being the tail-call which transports you from one room to the next.

Coroutines

A coroutine is another wonderful Lua concept. Very similar to threads, it provides a single line of execution within its own context. Several coroutines can work hand in hand, for example in a producer-consumer relationship. You can create, yield and resume coroutines.

Take the example of a producer coroutine reading lines from a file, passing the text to the consumer coroutine. The consumer coroutine receives from the producer.

function consumer (prod)
    while true do
        local x = receive(prod)
        io.write(x, "\n")
    end
end

The send and receive functions provide the gates on each side of the read-write pipe.

function receive (prod)
    local status, value = coroutine.resume(prod)
    return value
end

function send (x)
    coroutine.yield(x)
end

Finally, the producer-coroutine looks like this:

function producer ()
    return coroutine.create(function ()
        while true do
            local x = io.read()
            send(x)
        end
    end)
end

Coroutines can be used for many other things, like iterators or non-preemptive multi-threading applications.

What about Perl?

An interesting challenge could be to see how Perl might be used to implement similar functionalities like those that Lua does natively. As Perl advances and becomes more powerful, it makes sense to see how other programming languages work, and whether or not Perl could be extended to include more advanced concepts.

You'll also want to check out meta-tables and meta-methods, which I believe could be made part of Perl in the not-so distant future.

Official Website

If this all sound confusing, get the book where it's explained clearer and in more detail.

Be sure to check out The Official Lua Website where you will find alot of documentation and tons of examples to whet your curiosity.

Recent Assets

  • Zuma.jpg
  • Mysterious-clouds.jpg
  • Kiffin-golf-eight-mos-small.jpg
  • Daily-run.jpg
  • Golfing-in-the-fog.jpg
  • golf-flag-snow.jpg
  • kiffinplane.jpg
  • davis-love-putting.jpg
  • Lunatech-foursome.jpg
  • Miraculous putter
  • Early-morning-golf.jpg
  • eagle-putt-hole-6.jpg

Recent Comments

OpenID accepted here Learn more about OpenID

Information

This personal weblog was started way back on July 21, 2001 which means that it is 7-21-2001 old.

So far this blog contains no less than 1893 entries and as many as 1842 comments.

I graduated from Stanford 6-5-1979 ago.

I first met Thea 6-14-1980 ago.

Believe it or not but I am 10-11-1957 young.