Category: Perl

 | Perl | 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.

 | Perl | 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.

 | Perl | 1 Comment

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.

 | Perl | 11 Comments

During my lunch break I meandered my way along the canals and through the narrow alleys to the local book-store.

This book-store is pretty big, five floors filled with millions of books. They've got this huge eating area which always smells delicious. My favorite section of course is the computers section (followed by modern literature, and then science, and then psychology).

Several weeks ago, I was there and noticed that there were very few Perl books on the shelves. Only two measly copies of Mastering Regular Expressions and one copy of Learning Perl whose cover had an ugly crease in it.

With a rather disappointed look on my face, I asked the guy how come there were so few Perl books. He shook his head and told me that lately they just weren't that popular. The previous day he had re-ordered some titles, and they'd arrive in about a week or so.

Well there I was three weeks later, and there was not a single Perl book to be found. Just an empty spot becoming ever so cluttered with overflowing JavaScript and ActionScript books which were taking over the section dedicated to Scripts. What a sad day for me.

I believe it is high time to come out with some new titles. If I had more time on my hands maybe I'd try to write a book. There are many talented writers out there and perhaps they are coming up with some creative variations on the subject.

Hopefully with all of the new and exciting Perl-ish happenings on the rise, there will be a new barrage of literature appearing on the shelves some day in the not so distant future.

Until then I'll just have to be patient and scour the Internet looking for interesting tidbits in order to satiate my hunger.

 | Perl | 1 Comment | 0 TrackBacks

The Perl module CGI::Carp allows you to define a different error handler than the boring "A Software Error Occurred" one by using set_message() like this:


use CGI::Carp qw(fatalsToBrowser set_message);
...
set_message(\&handle_error);

Now all calls to die() are caught and sent to the user-defined subroutine handle_error() which will present the user with a nicer HTML page rather than the boring default one generated by CGI::Carp. Pretty nifty.

The only problem with this is when you are debugging. The contents of the HTML page are barfed up and scattered across stdout. This makes it hard to search through all of the HTML and find exactly where the error description, error code and line number is.

So what you need to do is define a simpler user-defined error handler which generates a plain-vanilla printf message.

How can the script detect whether or not it is in the debugger? Simple, just check if &DB::DB is defined. If it is defined, then call set_message() and pass it the simpler error handler like this:


set_message(\&handle_error_printf) if (defined &DB::DB);
...
sub handle_error_printf {
    my $msg = shift;
    print("$msg\n");
}

You're on your way to a happy and productive life as a Perl debugger kind of person.

 | Perl | 3 Comments | 0 TrackBacks

I've been doing alot of bash scripting the last few weeks. Struggling with all kinds of nasty problems and error handling stuff, I have discovered what a powerful utility this bash thing is.

Of course, when it comes to powerful scripting languages there's no substitute for Perl. Sometimes certain problems are a bit too complex for bash and it is nice to be able to fall back on Perl.

Let's say that I have an input file config.tmpl with a single line containing [% base_url %] and I want to generate a configuration file config replacing the value of base_url with $BASE_URL as defined earlier in the bash script, e.g. BASE_URL=http://www.kiffingish.com/utils.

One way of managing this is by using good old sed like this:


cat config.tmpl | sed 's!\[% base_url %\]!'$BASE_URL'!' >config

Sure this is fine and dandy, but what do you do if you have multiple lines in config.tmpl which need to be substituted on the fly? This is where Template Toolkit comes to the rescue.

I've added another line in config.in containing [% index_file %] which needs to be replaced with the value of $INDEX_FILE. A bash one-liner with the help of Template Toolkit works wonders:


perl -MTemplate -e '$t = Template->new(); $t->process('config.tmpl', {base_url => '$BASE_URL', index_file => '$INDEX_FILE'})' > config

If you are bit paranoid, you can extend the above one-liner with some error checking just in case:


perl -MTemplate -e '$t = Template->new() || die "$Template::ERROR\n"; $t->process('config.tmpl',{base_url => '$BASE_URL', index_file => '$INDEX_FILE'}) || die $t->error()' >config

Now if you are like me and even more overcautious. one more sanity check is in order. Always expect the worst, and if this worst happens, make sure that you can trouble-shoot the situation quickly and efficiently.

That's why at the beginning of the bash script, I also double-check that the Template Toolkit module is indeed installed.


# Make sure that the Template Toolkit is installed
perl -MTemplate -e1 &>/dev/null
if [ $? -ne 0 ]
then
    echo Template Toolkit is not installed, please install first.
    exit $?
fi

Isn't the Template Toolkit truly magical? That's why I use it very often to help automate even the most complex chores. Thanks alot Andy.

 | Computers and stuff | 0 Comments | 0 TrackBacks

I'm not about to claim that I'm some kind of expert on the subject, but I think it's fair to say that I've experienced my fair share of ups and downs over the years which makes me a little bit wiser.

Put simply the questions is how do we avoid failure when designing and implementing complex software products?

This is how I would answer that question.

  • The golden rule of thumb to avoid failure is to figure out early what the biggest risks to success are, and then to keep them in mind every single day. Keep this up until success is achieved.
  • Another key to avoiding failure is to admit openly when things start to go wrong, or better yet when you expect that things might go wrong. Don't hide the truth because you are worried that your boss will get angry or that you will lose face with your team members.
  • If things start to go better than expected, then celebrate it and make it publicly known. You guys have struggled really hard and deserve the recognition for work done well. Go out and have a party, but don't get too drunk because it's bright and early as usual the following day.
  • Feel proud of what you are making and treat it like your baby. Protect and cherish it, nurture it and play with it.
  • Admit defeat if needed and just start all over again. It is much better to restart with new insights than it is to plug along with an ugly product which keeps getting uglier, and finally slowly sink into quicksand.
  • Use sound metrics to measure progress and regularly decide where you, where you are headed, and possible obstacles along the way which will delay progress.
  • Learn from your mistakes, write them down, keep this list with you at all times, and reread it at least twice a day.
  • Finally remain open-minded, honest and embrace change, which will happen whether or not you want it to. Change hurts while it is happening, but afterwards it makes you feel a whole lot better.

One could easily say that the statements above apply to developing successful software products as well as to most challenges in life.

 | Perl | 0 Comments | 0 TrackBacks

There's been some talk lately about this new-fangled Apache module called mod_perlite a.k.a. the do-it-all like mod_php but better module for Perl.

Since by nature I am a curious kind of guy looking for yet another interesting challenge, I'm going to have a look at it for myself.

The idea behind mod_perlite is appealing. As a lightweight replacement for mod_perl, mod_perlite is much easier to install, embeds a Perl interpreter in high memory, supports the core CGI functions and has a much smaller memory footprint.

Good old mod_perl is very powerful indeed. I've done alot with it and think it's a fantastic beast. However, it is simply not accessible to the average bloke because it is complex and hard to learn. Have you ever realized how heavy the book Practical mod_perl is with its nearly one thousand pages?! Also, hosting companies are not eager to allow its subscribers to twiddle around with potential dynamite and having to support poor customers sucked down in mod_perl quicksand.

Hey, let's make Perl as easy as PHP for regular users to deploy and for web hosting companies to give as an appealing dynamic web application server stack!

For those masses of kind folks out there who are not computer savvy and not waiting for the headaches of fighting mod_perl, this makes mod_perlite a no-hassle and feasible solution for the low-end plain vanilla servers out there.

Imagine how screaming fast it could be on quad servers hooked up together to provide high performance dependable web solutions.

Perhaps even Lighttpd can come into the picture, why not? Hey now, that's an interesting idea. Writing Lighttpd modules is fairly effortless and hooking this up with Lua could become a real eye-opener.

Wouldn't it be nice to have an one-two-three web server setup that installs easily and just does what it is supposed to do? The blog server market is exploding and could very well benefit from this.

I've got some time on my hands for the next week so I'm going to check mod_perlite out for myself.

 | Perl | 0 Comments | 0 TrackBacks

Came home today to discover a package from Amazon waiting for me on my desk, and when I opened it I was excited to discover that the new Catalyst Book arrived.

I already started reading it, and I plan to devour it fully this weekend between my two golf tournaments.

In the meantime, I've already learned alot about the Catalyst Web Framework through weeks of hands-on experience at work, but I'm sure there's alot more extra stuff to learn by reading this fine book.

I'll be sure and write a (positive) review when I'm done.

 | Perl | 0 Comments | 0 TrackBacks

There were many interesting presentations given at the Sixth Dutch Perl Workshop earlier this year in Arnhem. The event was well organized and many people showed up.

I met many really interesting people there and even had the honor of giving my own presentation in front of the dynamic and fun-loving public. My presentation was called Perl and Scrum. Here's the powerpoint.

In the evening they drank some whiskey and played this weird card game called Fluxx.

Recent Assets