6 Jan 2008 acs   » (Journeyer)

The Practice of Perl II

Upon requesting made and continuing my posts about perl practicality, show here a very elaborated code, extract from classic book that I have reading again, Pike & Kerninghan Practice of Programming.

Yes, this book have a very interesting example of Markov Chains in perl.

For those that dont knowing about Markov Chains, this is a particular case in stochastic process, where previous states are irrelevant for prediction of following states, since that actual state is knowing. This technique is very used for generate random text, as in the book example, but, the author uses only cases that envolve two-word prefixes, for test effects.

The code used in the example, written in perl language:

$MAXGEN = 10000;
$NONWORD = ā€œ\nā€;
$wl = $w2 = $NONWORD;
while (<>) {
foreach (split) {
push(@{$statetab{$w1}{$w2}}, $_);
($w1, $w2) = ($w2, $_);
push(@($statetab{$w1}{$w2}}, $NONWORD);
$w1 = $w2 = $NONWORD;
for ($i = 0; $i < $MAXGEN; $i++) {
$suf = $statetab{$w1}{$w2};
$r = int(rand @$suf);
exit if(($t = $suf->[$r]) eq $NONWORD);
print ā€œ$t\nā€;
($w1, $w2) = ($w2, $t);

And more impressive is what the result is make of simple and rapid form, very rapid, in the final of chapter has a performance table where perl losing only for C implementation, other implementations are written in Java, C++/STL/Deque, C++/STL/List and AWK, being that have 150 lines of code in C versus only 18 in perl.

Well, I dont make apologies to perl, because I love C too, but, as the author says and define in the final of paragraph, scripting languages (perl, in this case) are a good choice for experimental programming and making prototypes, and I conclude, for rapid tasks and tests, perl is again language of my choice.

Syndicated 2008-01-06 20:43:18 from Jumpi's Notepad

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!