## miércoles, 28 de octubre de 2009

### quoting procedures in scheme and cl, first steps

Disclaimer: This is really newbie stuff for someone with 0.1 experience in scheme/cl, so bear with me.... I'm learning...

I've been a bit puzzled with the huge versatility of scheme functions, when reading the first chapters of this book. The code that made my brain halt was

((if (= 0 x) + -) 9 8)

Depending on the value of x, the result will be 1 or 17.

At first I thought why the symbols + and - shouldn't be quoted. But there's absolutely no need of it. Let's see how it works little by little. if we ask scheme (I'm using DrScheme with plain R5S5 here) about the plus sign, it answers it's a procedure, the same as if wrote a lambda function there.

For example, an expanded code, and somewhat less strange (to my eyes at least) would be:

((if (= 0 x)(lambda (x y)(+ x y))(lambda (x y)(- x y))) 9 8)

This would apply 9 and 8 to the resulting lambda. In that case, those lambdas do the same + and - do in the previous example.

Ok, I think I understand it.

In common lisp, it isn't that straightforward, because cl has 2 different 'namespaces' (probably it's not the right word but...), one for variables and the other one for functions, so if you want to eval a list as a s-exp, you have to use funcall.
(funcall (if nil '+ '-) 2 1)

Anyway, you can evaluate the if statement without the quoted + and - (if nil + -), but I haven't managed to make it evaluate the final sexp.

another way to modify a piece of code is accessing to a code (interpreted as a quoted list)
> (cons - (cdr '(+ 3 2)))(# 3 2)> (eval (cons - (cdr '(+ 3 2))))1

Well, for the moment it's all I've hacked with this kind of self-reference evaluations.

Btw, I've started reading HtDP, to start with an easy introduction to scheme. For the moment, the first 5 chapters are pretty easy to understand, but I felt I needed this basic background to fully understand the upcomming subjects. I'm kind of stalled in PLAI, where I understand most of the text I've been reading, but I'd like to do the exercices, and lately I don't have enough time to hack.

## lunes, 26 de octubre de 2009

### A la puta ruina

El Banco Popular presentó hoy (o ayer) resultados del tercer trimestre de 2009.

Es una pena que solamente ganó un 30% menos que en el mismo período del año pasado. Hecatombe, perdición, cataclismo!! Vamos a ayudar a los bancos, que pobrecitos, no tienen para sobrevivir.

El Banco Popular sólo ha ganado la ingente cifra de 630 millones de euros.

Me cagoen su puta madre.

## domingo, 25 de octubre de 2009

### PRACE and BSC training

Last week, I attended the BSC PRACE, "code porting and optimization workshop" given by some of its researchers.

The course was 3 days long, and I can say I quite enjoyed it.

First day, OpenMP . Full day of an openMP training. from quite easy levels to more complicated stuff, like tasks and other features only present in OpenMP 3.

Second and third day were not as productive as the first one, partly because of the subjects was not so much appliable to my daily work, and partly because of the speakers.

Alex Duran made a great OpenMP training course, and Xavier Teruel (my mus partner 5 years ago) helped us (Jdiaz, JMassanas, and $self) with great explanations when doing the exercises. I don't know if I can share the slides, but I'll ask BSC people, and upload them (If I can). We didn't do real complex things, but the overall feeling was that it's really cheap to try simple optimizations here and there in a large program (incremental optimizing), but converting a whole program into a highly parallel one is quite thrilling. We looked at private,shared,threadprivate... clauses to define the scope of variables. Follows a helloWorld example using OpenMP, with some calls to omp APIs, to return the number of active threads, max threads, or accurate time to do benchmarks. Then we took a look at 'task' clause (a bit more complex, but good for task parallelism). I won't publish the code in this post, as it needs a thought explanation I'm not willing to do now. If you feel the absolute need to see a omp code using 'task', mail/comment. After that, we looked at data parallelism, having a look at 'for', and different schedules. Here, we have a parallel matrix multiplication code, optimized using not only the typical 'for' but also using collapse. Some insights about balancing loads and other common problems ended up the session. ## viernes, 23 de octubre de 2009 ### insert code listings in latex I've been strugling with it for last 2 days, and finally found a solution (I should have googled before , and not so much blind guessing). Depending on what you're writing about, you probably will have to put code in your documents. Inserting code in latex is not that trivial, because you have to tell latex that a given block has to be left 'as is' (that means not formating it, not squeezing the newlines, indenting it correctly, and syntax highlighting it). My first attempts where quite hand-crafted solutions, mixing a verbatim environment and fitting it into a table with just one row and one column. Then I found a package called listings. It's a farily complex package, with lots of options and parameters, but for me, I just can use it nearly vanilla. \usepackage{listings}\usepackage{textcomp}\usepackage[]{color}\lstset{language=c++,tabsize=4}\lstset{commentstyle=\textit} If you want, you can use pretty complex configurations: \lstset{ language=C++,keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},identifierstyle=\ttfamily,commentstyle=\color[rgb]{0.133,0.545,0.133},stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},showstringspaces=false,basicstyle=\small,numberstyle=\footnotesize,numbers=left,stepnumber=1,numbersep=10pt,tabsize=2,breaklines=true,prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},breakatwhitespace=false,aboveskip={1.5\baselineskip},columns=fixed,upquote=true,extendedchars=true,% frame=single,% backgroundcolor=\color{lbcolor},} Then, you just embed your code inside a lstlisting environment \begin{lstlisting}[frame=trbl]{}class Funcio{private:map dict;public:Funcio(){};~Funcio(){};operator()(int param1){ if( dict.exist(param1)){ return dict[param1]; } double resultat; // calcular i omplir resultat ... dict[param1]=resultat; return resultat;}}\end{lstlisting} With this you can paste codes with a great look. As always, here are the sources I read to write this howto. Ah, I know the code in the screenshot does not work, but it's just a kind of pseudocode to illustrate memoize, closures, and the c++ functors aproach (a half-solution to emulate closures and stateful functions in c++) Bye! ### Bill and Ted Una charla de TED, genial como siempre, pero si cabe más emocionante y emocional que la mayoria. Mezcla de las curiosidades tipicas de Ted en aspectos de la musica y las emociones que provoca. Buena reflexion sobre las expectativas de duración y de 'vida' de las cosas. dying ? Nah.. you ain't seen nothing yet! http://www.ted.com/talks/benjamin_zander_on_music_and_passion.htmlj Ted++; Por otro lado, microsoft lanzó ayer windows 7. Noticia en el mundo. ## jueves, 22 de octubre de 2009 ### I CAN HAS GOOGLE WAVE OH HAI. Yesterday, I got my google wave account (I was kindly invited by ecarnevale). For the moment, I haven't played with it yet, and added to the fact that I only have a handful of contacts that have their wave account, I still have to see its power... Many friends already asked for invitations, but currently I don't have google wave invitations to give away. So from now on, you can find me at raimonster googlewave. Btw, contact me (by commenting) if you want an invitation (only if you think you deserve it ;) ) KTHXBAI ## martes, 20 de octubre de 2009 ### cmake tutorial. First steps We all have messed up with makefiles, and most of us have been really annoyed with them. Writing them is awful (and all that space-vs-tab thing...yuk!), and maintaining them for medium projects is not very pleasant either. I've tried to understand autotools a couple of times, but never made through. Difficult and outdated docs, and when I passed the 'hello world' project, I didn't find it very intuitive. It's a pity when you have to study a tool for a month to get simple things done. cmake tries to make the process easier while improving the dependency tracking between files. It's also multiplatform and multi-compiler , so you can use it for later use of gnu make, or VC++ projects. First, we can start with a trivial use case. Good old 'Hello World'. Well, you imagine the code. #include <stdio.h>int main(int argc, char const* argv[]){ printf("Hello world!\n"); return 0;} Save it in a file called helloworld.c and we're ready to write a file for cmake configuration. Create and edit a file called CmakeLists.txt and add the following lines to it PROJECT(helloworld C)SET(SRC helloworld)ADD_EXECUTABLE(helloworld${SRC})
Then just execute "cmake ." in that directory, and you'll see you have a Makefile (and lots of other files and dirs. For the moment, what you have there is already usable. For example you can use make clean too.

After this baby steps, we can go to a more complex example. Let's use a c++ example, with a main file and a class file.

/*****Hola.cpp ****/#include "Hola.h"using namespace std;void Hola::saluda(){std::cout << "saludo" << endl;return;}/*******************//*****Hola.h ****/#ifndef  HOLA_H#define  HOLA_H#include <iostream>class Hola{public: Hola() {}; ~Hola() {}; void saluda(void);};#endif   /* ----- #ifndef HOLA_H  ----- *//*******************//*****projecte.cpp ****/#include <stdio.h>#include <iostream>#include "Hola.cpp"using namespace std;int main(int argc, char const* argv[]){Hola* a = new Hola();a->saluda();return 0;}

Then we'll have a little more complex CMakeLists.txt file

PROJECT(projecte CXX)add_definitions(-Wall -W -ggdb)SET(SRC projecte)INSTALL(FILES projecte DESTINATION bin)ADD_EXECUTABLE(projecte ${SRC}) A few observations: • Note the change in the first line from C to CXX. • add_definitions directive is to add flags to the compiling process. • INSTALL directive enables 'make install'. DESTINATION bin tells to install in$prefix/bin (usr/local/bin normally) .
• We don't even have to mention Hola file, because it's included by projecte.cpp, and cmake will track the dependency, and build only in case of modification.
Now we'll build the same program compiling Hola class into a separate library. That's how the CMakeLists.txt file looks like

PROJECT(projecte CXX)add_definitions(-Wall -W -ggdb)SET(LIBSRCHola)SET(SRCprojecte)INSTALL(FILES libHola.so DESTINATION lib)INSTALL(FILES projecte DESTINATION bin)ADD_LIBRARY(Hola SHARED ${LIBSRC})ADD_EXECUTABLE(projecte${SRC})TARGET_LINK_LIBRARIES(projecte Hola)

Everything is nearly self explanatory, right? well, you can then rerun 'cmake .' , and a new Makefile will be generated.

There are some good tutorials out there. Most of what I found explain the same in different blogposts with some example CMakeLists.txt

Cya!

## lunes, 19 de octubre de 2009

### Leones polares

Estoy tan nervioso que me he ido a fumar un 'cigar' a la calle.
Con ese fresco pensaba que me despertaría, o al menos me refrescaría un poco.

Y resulta que no, que sigo igual que antes.

Dice Punset que el ser humano es el único animal tan 'avanzado', que puede hacer que su cuerpo esté en el mismo estado de tensión que cuando le está a punto de atacar un león, aunque el león sólo esté en su cabeza. No hay ningún puto león, ni ninguna hiena, ninguna cuchara, ni nada por el estilo. Estás en casa, aburrido y sin que pase absolutamente nada a tu alrededor, y sin embargo, cierras los ojos, ves el león de frente, te enseña los dientes, y tu arrancas a correr.

Pues colega, voy a soltar el yunque y voy a seguir corriendo hasta que esté bien lejos, pero no me gusta un puto pelo estar huyendo de fantasmas.

## jueves, 15 de octubre de 2009

### Mis palabras contra mi

Hay palabras que quieren estar en tu texto.
Aunque no peguen.
Aunque tú no quieras su significado.
Creen que el texto les pertenece,
y que tienen derecho a pedir aparecer.

Porque ellas estaban en tu mente antes,
porque ellas son más bellas que las otras.
Y tu les abres la puerta y les dices que 'pasen'
Pero que no toquen las pelotas.

Y ya no se si soy las palabras que digo,
o soy las palabras de las que escribo,
o un puto actor de 3 al cuarto,
al que se le han acabado las ganas de hacer rimas, cojones ya.

### How I use Emacs + irc (or erc for dummies)

Given a certain interest by some about using emacs as an IRC client, I'll try to explain how I use it and the configurations I use.

First thing to know is erc. erc comes bundled with emacs from 22 on (IIRC). The way to run it is fairly intuitive to any emacs user: M-x erc

After that command, you'll be asked some questions, but defaults are ok for most situations (freenode, yourUser, :6667 ).

Tip: If you happen to be behind a corporative environment (ehem, $uni/$work) , try ports 8001 or 7001.
when you're in the main freenode buffer, you can use IRC commands like /join /nick /names (when in a channel) /query /dcc .... but you better learn some shortcuts.

As most major modes, erc shortcuts start with c-c. then:

c-c c-j : /join

c-c c-n : /names

When something new happens in any erc buffer, it will apear in the modeline, and you can move to it with old c-x b , or c-c c-b will use a cooler way to change between erc buffers (only erc buffers, using ido-mode and with acceptable guessing).

if you have to visit many erc buffers, you can use c-c c-space, to travel to erc buffers with changes. after the last erc buffer with changes, you'll go to the last non-erc buffer you where last time. Great, isn't it?

you can move pretty well around erc buffers. Now the autojoin thing.

(require 'erc-join) (erc-autojoin-mode 1)(erc :server "irc.freenode.net" :port 6667 :nick "mynick" )(erc :server "irc.perl.org" :port 6667 :nick "mynick" )(setq erc-autojoin-channels-alist   '(("freenode.net" "#channel0" "#channel1")("co.uk" "#channel2")))

With this config, every time you start emacs, it'll start an erc session and join automagically to channel0 and channel1 in freenode, and channel2 in perl.org server . if you don't want to autojoin automatically, well... deactivate autojoin.

Another good trick is the readonly channels.

That's all for now. If you investigate on erc, you'll see it can autosave logs, and so. It's quite powerful, but I think don't have the need for so much power :)

### Me perdí woodstock, cause I was high...

Estaba haciendo un poco de ego-busqueda por google, para ver si mi post del hackathon-breakout se habia propagado de alguna forma por 'el internet'.

Pues, cual es mi sorpresa cuando hoy veo que había ganado una entrada para el pre-estreno de la penícula 'Destino Woodstock' en un concurso-mailing de radio3... para hace 2 semanas.

No es que fuese fumao (yo no consumo droja), lo que pasó es que yo iba confiando en que mandarían un mail en el caso de ganar, y resulta que no, que tenia que haber mirado en este link , para ver que sí, que era uno de los 150 seleccionados para ir con una pareja a ver la pelicula de marras.

Pues visto lo visto, acabo de suscribirme un google alert que buscará mi nombre por todo 'el internet'... osea que cuidado lo que dices de "raimon grau"..... Big Brother is watching you..... Al menos así me enteraré cuando me pongan una multa, o cuando me den un premio nobel :D .

## miércoles, 14 de octubre de 2009

### Breakout Cornella and Smalltalk-fluidDB hackathon

I just came back home from the Breakout event (Work outside your office initiative).

The balance is really positive. Although not having comunicated or met many people, I think I talked, met and saw after long time the right people :) .

We had internet connection just 20 minutes after arriving there (WIN). Just after that, I could download all the pharo stuff (vm, image and our starting codes). We had a small brainstorm of what we should do during the day, and reread the docs to clarify some things.

After a few minutes, Terry Jones broke into the party (WIN), and we sat down again in the grass and had a master explanation of fluiddb philosophy and expectatives. Then there were lightning talks which I attended partially because I found an 'old professor' of mine (Toni Cañabate, a great and wise guy) and we got distracted of the talks (WIN) . Xavier Noria then arrived, and explained to Jordi Delgado and me some gotchas he had to solve for his Net::FluidDB lib. A perl scalar internals masterclass in 15 minutes.WIN.

After hacking a bit more, we had lunch and some small talk (in the chitchat meaning). Terry and Xavier Noria were with us there too.

We spent the afternoon hacking a bit more, and we finally got to create, retreive, and get the info related to namespaces (Jose Garcia and Bernat Romagosa WIN). Although it's very little compared with what we'll have to write (FAIL) , we 'got' the concept, and we managed to have the basic comunication flow (POST and GET). Apparently, the rest of the lib (at this low-level lib) will be tunning the queries, but the conceptually difficult things are done (or at least, we like to think that).

Btw, fxn, the /(p(erl|ython)|ruby/ guy, explained me some tricks he used in his Net::FluidDB perl lib, for example, moose at its full power (WIN). That means lazy constructors, roles and the like. I'll post something about that soon.

I still don't have any photo (FAIL), so I'll update the post when I find the f*cking usb-mobilePhone wire that I think I lost (FAIL). Fxn has a twitt showing a photo

Overall it was pretty good, I only regret not having had the time to program a bit more (FAIL)... but well....

PS: I don't want to end with red colour, so I'll say that at the WTC (Breakout place) there were *lots* of nice chicks. Lots more than at my $workplace, so Breakout WIN and Citilab WIN for organizing it. PS: I'm exhausted of adding links. If you want more links in this post, tag a word with a link and refresh. .. ... ..... You wish :) ## martes, 13 de octubre de 2009 ### Stop tracking a file in Mercurial Since I read The definitive guide to mercurial, I've been using mercurial daily at$work , and following a branch-per-feature workflow with more or less success (I'm very satisfied myself, but I keep forgetting the commands).

Today I took a project I was coding some time ago, and when I did my first commit... I saw mercurial was tracking a binary file I didn't particularly wanted to track (some temporal .o in CMakeFiles dir).

Here's what I did to untrack ChironEA.o file:
rgrau@ares [ ~/chiron ] %hg commit -m "FooBarBazQuux added"rgrau@ares [ ~/chiron ] %hg virgrau@ares [ ~/chiron ] %hg rollbackrolling back last transactionrgrau@ares [ ~/chiron ] %hg remove src/CMakeFiles/ChironEA.dir/ChironEA.o                  not removing src/CMakeFiles/ChironEA.dir/ChironEA.o: file is modified (use -f to force removal)rgrau@ares [ ~/chiron ] %hg remove -f src/CMakeFiles/ChironEA.dir/ChironEA.oremoving src/CMakeFiles/ChironEA.dir/ChironEA.orgrau@ares [ ~/chiron ] %hg commit -m "FooBarBazQuux added"

Little by little, it seems I'm starting to do things the right way (tm).

Btw, I've packaged latest mercurial version for vectorlinux (yeah, that little fast distro I happen to use and recommend)

### Good API Design

A great talk given by Joshua Bloch (google engineer) presented at Javapolis 2005 and OOPSLA 2006 about tricks and key points to keep in mind when designing an API and SPI. The recording is from Javapolis conference, and recorded by infoQ (the greatest platform to watch talks at present day).

http://www.infoq.com/presentations/effective-api-design
http://portal.acm.org/citation.cfm?id=1176622
http://www.infoq.com/articles/API-Design-Joshua-Bloch

I have to confess I didn't thought about most things that Joshua says there :( . Some things I do right (intuition?) and some of my APIs suffer from lots of bad habits commented here.... Well, It's never too late to learn...

## lunes, 12 de octubre de 2009

### gtd and speedreading

As you know, I've started to read the GTD book. For the moment it's being a fairly good read. Very clear concepts, written in a very straight way, and there's little to no 'boilerplate'.

Another book I recently started (that means, this very same weekend) is 'Teach yourself speed reading'. Another clear book with some key concepts to boost the reading proces.

Both books have some concepts in common (in fact, efficient reading is a particular and speciallized version of getting something done).

For example, knowing your concentration and don't forcing yourself to do things you will do better in other conditions. Or the 'prepare' or 'study your enemy' part. both books put lots of emphasis in this preliminar concept of knowing the 30000 feet picture.

Part of this phase is asking you "what you will get of completing this project (reading this book/article)" . Once you achieve it, stop reading. That's a very pragmatic approach, but GTD also have the 'next actions' list, where there are sentences of phisical actions that will move the project on, towards the desired direction.

They both sound like an agile methodology for life, don't they?

Well, I wanted to train a bit of speed reading, so I started to write a program to skim texts. ATM it uses opengl with glut. I'll post the code when it is something half decent.

Warning! c code ahead!!

Here's a good opengl survey about fonts.

http://www.opengl.org/resources/features/fontsurvey/

## sábado, 10 de octubre de 2009

### Benchmarking perl

I had a little code that worked perfectly for what it had to do (process every line in a file, and get a list of unique lines (after being processed)).

The 'process' I had to run on every line was a simple substitution, so I thought of Algorithm::Loops. I used it and worked really well, but then I thought about performance, and tried some other approaches:

Well I could clearly see that while version is the winner, and it really makes a big difference. I suppose this is because Filter takes <$fh> as an array (in list context), and that is slower than the iterator version (just guessing). Here's the code: And the results:  Rate filterChomp match regexBarraN whilefilterChomp 9.49/s -- -19% -24% -64%match 11.8/s 24% -- -6% -55%regexBarraN 12.5/s 32% 6% -- -52%while 26.0/s 174% 121% 108% -- Well, appart from keeping the while version for my app, now I have a template for bencharking perl codes. Following the same technique than in one of my other perl posts, I've written a template file to be easy to paste in a .pl file from vim. ## viernes, 9 de octubre de 2009 ### diario de sabadell PWNED! I just browsed to www.diariosabadell.com, and the top front page seemed ok... In the middle of the page..... PWNED!!! Last august, there was a massive spanish-journal-sites hack with similar photos (I was at YAPC::2009, so it was 3rd-6th Aug). Journals sites seem to attract hackers... UPDATE: Keeping it -Ofun 4 hours later, I can't decide if the whole journal DiarioSabadell is a total joke , or they haven't noticed they are beeing fooled. ### GTD tools: remind As you probably seen in one of my last posts, a few days ago, I started David Allen's Getting things done book, and I think I'm starting to grasp the pragmatism of the method. I'm nowhere near fully implementing it in my life (I've only read 1/3 of the book) but googling a bit, I see tools and methods that people use. Some time ago, I installed remind on my box, and tried (read FAILED) to use it regularly, but now I think it's time to give it another spin in order to manage my timmed 'stuff'. Remind is a commandline tool (O RLY?, YA RLY) that helps you to manage your schedule/calendar events. One of the big wins of remind is that everything is stored in a plain text file, making it really easy to be parsed or edited from everywhere. The default file for reminders is ~/.reminders . Let's see a sample reminder. REM Oct 09 2009 MSG HAZING CHEEZBURGRS WITH LOLFRIENDS.% If I run remind command, it will print the MSG line. Say you want it to mail your friends about your cheezburgr event. REM Oct 2009 RUN mailfriends.sh Easy, right? Now let's go with periodic events. For example, I'd like to know when I have the next smalltalk meeting (every tuesday), and want to be alerted the day before (sometimes the same day is too late) REM Tue +1 MSG Smalltalk meeting at Citilab %b. Or Next Perl Mongers Barcelona meeting (last thursday of every month) REM Thu 1 --7 +1 MSG PerlMongers meeting %b. I think this deserves some explanation. Thu 1 matches when both Thu and 1st day of the month are true (That is the first tuesday of the month). Then the --7 substracts days to the previous date. That means the last Thursday of a month. There are ways of setting reminders for a given day AT a given time, and set a duration, but I think that's all I need for this part of the GTD implementation. Btw, If you want more info on remind, there are some good howtos and tutes online, and remind has a mail-list too (the mail archive is only accesible to subscribers though). ## miércoles, 7 de octubre de 2009 ### Time to change passwords! OH HAI. Thousands of hotmail passwords have been magically revealed on the intertubez. Mabe iz time to change ur pazz , just in case. In fact, when you last changed your hotmail password? O RLY? Never? yay, then you're like me, and kept your password since 1995. More info in this link. KTHXBAI. ## lunes, 5 de octubre de 2009 ### Learning to Learn When talking about curiosity, and learning in general, I've got itchy feet. That's a well known fact. Unfortunately, it's also a known fact that my perseverance in a field is not very notable. I've only managed to keep the interest for a long time in a handful of things (from 16 y.o. to 18 in reverse engineering, from 20-now optimizing procedures (say bash, vim, zsh, screen, tiling wm...) and since I was 24 on I've been quite fond of perl) . I get amazed by new technologies, or programming languages too often, and although that makes me a very aware person of the state of art, I'm not an expert in any of theese. I call myself the 'master of hello worlds' . Examples are: • Io • Haskell • Smalltalk • Catalyst • Lisp • Scheme • zsh • factor • emacs • ...and a looong list... For some time I've been addicted (among other things) to trying new programming languages, and read a good amount of literature about those (paradigms, implementations, tips 'n tricks)... But lately I've felt the need for something more general. A kind of 'programming best practices', or some patterns book (not the GoF one but one I can read from cover to cover). I took a look at some smalltalk book, or more generic books (O'Reilly beautiful XYZ) . But I wanted to go more meta. And remembered a thing I wanted to do since I was about 20. Empower and speed up daily tasks. Some time ago I read 'Mind Performance Hacks', and was good enough, but most hacks weren't appliable to my daily life. As an example, this weekend, I started to read articles of: • lisp • Catalyst • squeak • FluidDB • Perl As you see, I need to focus (or a girlfriend). And organize myself. And Thought that in order to focus, I'll read David Allen's "Getting things done" once for all. It's been in my TODO list for some time and now I feel it's the moment. So my TODO ReadList, has grown by 2: GTD, and a Speed Reading book. That's not a very good start :) . Meta-procrastinating Rulez! Bah, I doubt this post can be useful to anybody but me... If you've read until here, sorry ... that's all... at least you can google some of the words I put here, and learn real things. Byez PS: Want more titles? ask in comments. ## domingo, 4 de octubre de 2009 ### Perl 5.10 regexes It's been around for 2 years (Perl 5.10 was released in December 2007), but I mostly used it as 5.8.8 (I didn't think that my perl level would make any difference between so near versions). I've seen some of the improvements from 5.8.X and I think there are some things that even for newbie/intermediate perlers like me might be of interest. Say "eeeoo" Ok, this is probably a feature that won't make you migrate to 5.10, but it's there, and starting using it is trivial. Put it short, For all x , say x == print x ,"\n"; it's shorter to write, and you don't have to write the "\n". It's like writeln or println of other languages. We're done with that. Defined or I love shortcuts, from ||= to 'open or die' . I think it's a very elegant way of avoiding an extra if. As you know$x ||= 'foo' is the same as $x =$x || 'foo' , so if $x evaluates to false, then$x becomes 'foo'. The problem with perl is that 0,'' (that's empty string), and undefined , all evaluate to false. //= is the way to check if something is defined in a shortcut way.

given/when

Finally, perl had a switch/case statement. In fact, to emulate the 'switch/case' statement from other languages, we could use dispatch tables (being much more flexible than java'sor c++'s one). Given/when is far more flexible and advanced than usual (comparison by ==) cases. It uses the new smartmatch operator, allowing to compare different type of things and doing 'The correct thing" (tm)

Smart Match

Ok, so what's the smart match operator?. It's a binary operator whose syntax is ~~ , and it tries to compare left operand with right operand in a DWIM (tm) way.

For example, %hash ~~ $scalar searches if exists$hash{$scalar} . Array ~~ Regex , greps the array with the Regex. You get what I mean.... for more info, look at perldoc perlsyn. Regexes Now what had to be the main topic of the post (that will end in just another section). As you can see in perldoc perldelta of 5.10.0 , there have been many improvements on 5.10 regex engine. I'll only cover a few of them basically because of 2 things: 1) I don't understand everything there 2) laziness The most practical new feature is "possessive quantifiers". We know perl regex quantifiers are greedy unless we put the '?'. That works when the given match has lots of possible matches, but there's a backtracking involved that maybe you don't need. Maybe you want really greedy matches, as in greedy algorithms (when a decision is made, it stays forever). If you add a plus sign just after any quantifier, you make it 'non-backtracking', so if it 'eats' a character, it won't permit it to be in the next token in any circumstance. I've come with a stupid example. Say we want to match pairs of letters in a string, and have the last pair or the last one (odd length) in a separate place:$_='a'x6;
m/^(aa)+(a+)$/; print$2,"\n";

$_='a'x7; m/^(aa)+(a+)$/;
print $2,"\n"; what happened in the first case was that the pair matching advanced untill the end of the string and when noticed that the last (a+) had to match something, it backtracked twice until both conditions where satisfied. The second example was easier because when it couldn't match a pair, a spare 'a' was there to fit in (a+) slot. Now we'll try with ++ .$_='a'x6;
m/^(aa)++(a+)$/; print$2,"\n"; #error

$_='a'x7; m/^(aa)++(a+)$/;
print $2,"\n"; #ok As (aa)++ makes it unbacktrackable, there's no match. So, keep in mind it can really speed up things, but it won't match same things, so be aware of this. Another regex new feature is named captures. now you can name captures with (?<foo>pattern) . after doing the match, you can retreive the matches through the %+ hash :$+{foo} .

There are other improvements, but I'll leave them for now.

Only tell you that 5.10.1 is already here, and just improved on that, allowing more funny ways of using smart match and given/when. Perl 5.11 is out too (but it's a development release).

If you're hungry of perl new things, have a look at Perl 6. If you want more regex hardcore, take a look at Damian Conway's Regexp::Grammars.

That's all for now. Thanks for reading.

## sábado, 3 de octubre de 2009

### squeak (pharo) + fluidDB + UIBuilder

There hasn't been much activity in my blog last week. That's partly because I was on vacation, but I haven't stopped hacking completely.

For instance, I could finish reading 'Effective Perl Programming', by Joseph Hall and Randal Schwartz. A very good book, full of little tricks on how to optimize perl codes, or good practices, or even tipical gotchas perl 'offers' you.

It's a very practical book, and I could apply what I learned from the first minute I started reading it. Thanks to CDamian for giving me this book. If you happen to know me, and you want to read it, just drop me a line.

I've been reading a bit about FluidDB, the new database technology with wiki essence. At GTS (grup de treball Smalltalk (Barcelona smalltalk users group)), we thought it'd be a good idea to write a library to manage fluidDB from squeak. We mostly want to port fxn's perl lib to squeak.

We chose fxn's one because his implication on fluidDB project. It seems to give us more confidence.

Anyway, I had looked at some docs last week and commented some things on gts meeting, and this week, when I returned from holidays, I saw Jose had already written a mini lib to query fluidDB sandbox. For the moment, it's a simple lib that only allows GETting queries, but it's ok for us to get used to fluiddb usage.

When I was trying it, I got tired of modifying the query string, and thought of doing a GUI to ease my work. Then nullPointer's UIBuilder called CLFramework came to my mind. I installed it through monticello, and ran it. No problems so far.

I found a little bug that got fixed immediately (It's great when devs are around at IRC, isn't it? ). Well, and here it is! a fully Barcelona pseudo-application, unifying FluidDB, with some gts work.

The point is that writting a handful of lines, I got something quite pretty and acceptably useful. I also had the oportunity to learn how to make simple GUIs using nullPointer's CLFramework (and spotting a bug) that always adds -Ofun to the journey.

Now the screenshot...

Have fun, and keep hacking my friends.

More to come on fluidDB next week (I hope so)

PS: Ah! When I was trying to fix the bug, I looked at some keyStroke methods, and discovered that cmd-Del ( alt-Del ) closes the foxused window in pharo. It's like Alt-F4 on most win/linux systems. You're welcome

## viernes, 2 de octubre de 2009

### Great read for programmers and non-programmers

Today I read a Matt Trout's post that isn't directly related to programming, but it's brilliant nonetheless. Being a programmer or without beeing one, please read it and enjoy. I think matt shares great things with this post.