miércoles, 12 de mayo de 2010

You can stay at $HOME, Perl :)

Evolution is the way to keep up with times, and lots of things are happening in the perlsphere lately:
  • Perl 5.12 went stable on April 2010, with lots of fixes, and a few new features. See the deltas.
  • Rakudo is making progress at a good rate, with new contributors, and it's getting faster and more complete every day. Parrot guys are doing a great job there too.
  • cpanminus seems to be the next big thing of the language, and it's a perfect companion of local::lib and even perlbrew.
Cpanminus is miyagawa's (quite successful) attempt to simplify CPAN.pm, in a DWMI-Y way. by default, it follows dependecies, uses your prefered path to install modules (it knows about local::lib) , and will just install and get out of your way. It's better for perl newbies (and pseudo-newbies like me) and speeds up the installation of the whole environment.

local::lib is one of the wizard mst's magic spells to enable local repositories of libs per project. That means you can attach cpan libs to your apps, and then control the exact version you ship with each app.

the complete install process of the environment is the following:


mkdir ~/myperltmp
cd ~/myperltmp
wget cpanmin.us
chmod +x cpanm
wget http://search.cpan.org/CPAN/authors/id/M/MS/MSTROUT/local-lib-1.006000.tar.gz
tar zxvf local-lib-1.006000.tar.gz
cd local-lib-1.006000
perl Makefile.PL --bootstrap
make test && make install
echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc


And now you're ready to go.
./cpanm DBIx::Class
./cpanm Moose

And with 0 questions, you'll have DBIx::Class and Moose in your ~/perl5 directory.

If you added the last line to your .bashrc, then everything should work. You can use local::lib "~otherpath"; to have multiple scenarios to try your modules/apps on. Next thing to try is perlbrew, but that's for another day.

Mainly I extracted the info from here and here (and perldocs, of course)

Before leaving, let me leave you with a great talk by mst. Full of info, and full of lolz, and nearly no swearing (Wow! surprise!)

miércoles, 5 de mayo de 2010

Comparing functions. How similar are we?

Sometimes I have two functions, maybe in different subclasses, and I would like to do a diff on them, because they look very similar but not the same. Most of the times, they are come from a past copypaste, so variables have the same names.

What I want to know then is what has really changed, or if they changed at all.
#in file foo/bar.pm
sub normalize {
my ($self) = shift;
$self->attr($self->attr / $self->total);
}

#in file foo/baz.pm
sub normalize {
my ($self) = shift;
$self->attr($self->attr / $self->total +1);
}

Emacs comes to rescue!

We'll use two great emacs features, narrow and ediff.

narrow lets us hide uninteresting parts of a given buffer. It's usage is pretty simple: Mark a region, m-x narrow-to-region (or c-x n n). There's also a shorctut, and there are predefined narrowings, like narrow-to-defun... you know, emacs butterflies.

Once you narrowed two buffers to the interesting regions, you can use ediff (m-x ediff-buffers) and select the two buffers you want to narrow.

To widen the narrowed buffers, you can 'm-x widen' (or c-x n w) to see the complete buffers again.

Tip for ratpoison users (or any other tiling wm user): (setq ediff-window-setup-function 'ediff-setup-windows-plain) in your .emacs will tell emacs to open the ediff window in a different window, but not opening a new frame. (window and frame have inverse meanings in emacs world than in the rest of the world)

theese would be the steps:

  1. open bar.pm
  2. go to normalize function.
  3. c-m-h (mark-defun)
  4. c-x n n
  5. open baz.pm
  6. (steps 2-4)
  7. m-x ediff-buffers
  8. select both buffers (emacs will suggest them already)
  9. check diffs
  10. q (quit ediff-mode)
  11. c-x n w (widen)
  12. go to the other file, and widen again.
  13. You're done

Endnote: Although being a big fan of vim myself and having used it for 5 years, these features available in emacs by default, are not (at least easily) doable in vim. emacs, the kitchen sink, and m-x butterflies DO have their uses :)

viernes, 30 de abril de 2010

Fiuchar is nau

Es acojonante interactuar con el mundo. Unas veces ganas, otras no, pero interactuas. Y eso mola, no me jodas.

Lo que recientemente me sucede, y me doy cuenta, es que el futuro esta íntimamente relacionado con el presente, y aunque eso parezca una trivialidad, no siempre soy consciente de ello.

En la historia que no sale en los libros, la del día a día, la mía, y seguramente la tuya, uno mismo es el prota de su película, y si no esperas nada más de ella que ir pasandolo bien minuto a minuto, pues no importa mucho a donde te lleve el proximo capítulo. Carpe Diem.

Pero no hace falta tener previsiones a años vista para ver que tus pasos no son gratis. Cada movimiento es un turno, y eso ya no vuelve. Y la jugada que empiezas ahora, te condiciona tu siguiente turno. Y pasar no entra en las reglas del juego. Llamémos a este epsilon de tiempo, "el proximo turno".

Una entrevista de trabajo mal llevada, te cierra puertas a currar, a dejar el curro, o a cambiar de ciudad.

Un policía que casi te pilla, te podía haber jodido tu expediente, o tu carnet. Y tu estabas jugando en el juego. Un borracho que por la calle te pega un puñetazo porque ha ganado su equipo, te deja, a parte de en el suelo, te deja pensando en que cojones haces viviendo un día a día, que no te lleva a ningun lado, porque simplemente apuntas a media altura, apuntas a mañana. al proximo turno, pero solo con llegar ya te basta.

Un paso mal dado, te puede dejar cojo, y no poder irte de viaje, aunque ya hayas pagado tu billete. Pero esto no es como Dallas, donde te puedes inventar que la muerte de JR era un sueño. Los turnos pasan, y cada jugada es una opción de encarrilar, o cagarla.

Este próximo turno (futuro immediato) se crea a partir de esta gran bola de mierda que es el presente, y que va ladera abajo, llevandose por delante todo lo que pilla. Y es tan grande y gorda, que uno no la puede parar conscientemente. Digamos que es una version del S.XXI del concepto del "train of knowledge"(al final) y Quality que conocí en Pirsig, paralelismo del tren, pero remasterizada, actualizada, y con 7 segundos inéditos. Los del puñetazo.

DOCS or GTFO


Ok, you hate documenting. But it's part of the deal.

As you may know, there are tools that generate browseable documentation provided you document your code in a proper way.

Perl is no exception, and you can convert POD documentation to html, formatted plain text, LaTeX, etc...

To ensure you documented (at least, put the boilerplate) every non private function in your code, there's a module called Pod::Coverage that checks for undocumented functions, parsing your code, parsing your pod, and doing the match, and the diff.

Once that we're at it, we can bundle the check as a test for our application, and, in fact, there's Test::Pod::Coverage, that is exactly what we're looking for.

Ok, let's write a minimal module (BankAccount will do), using the right tools for each job.

module-starter --module=BankAccount --author="Raimon Grau" --email=raimonster@gmail.com --builder="Module::Install"


This will generate all the boilerplate and the directory scaffold needed, and it will include (at least if you have both packages installed).



This code will fail the pod coverage test, because the method withdraw is not documented.

Well, we have a new tool in our toolbox, that makes sure at least every method has its associated POD documentation. The module won't force you to document subs starting with underscore (thank god for DWIM). There's also other modules that build on this, like the one RJBS explains here.

lunes, 26 de abril de 2010

Iterator::Simple, as simple as it gets

We're all feeling spring is coming again. That's not new though, so you could have guessed that after winter, spring was about to come.. ¬¬

We could build a circular list to retrieve a list of consecutive seasons, but as I discovered
Iterator::Simple, Here follows a stupid example of its usage.



We can also wrap an iterator, "á la" stream (I'm reading the stream chapter in SICP, and nowadays, I can only think in streams :p ), delaying the evaluation of the wrapping until the given elements are needed using imap. We also have ifilter, igrep, and so.

Here's a code that wraps (or decorates, in python slang IIRC) our iterator modifying the string returned, and it limits the iterator to 6 seasons.

miércoles, 14 de abril de 2010

Versioning in squeak/pharo using Monticello

Lately I've been working on a simple website I'm doing in smalltalk. It's not a complex thing, but it's someway new being my first serious website I've done.

To build it I'm using pier and seaside. And it's mostly fantastic. But sometimes, all of the sudden, some unknown error occurs and my image freezes. And my last codes are lost. No way to recover it even using the recovery tool.

So I remembered something Mr. Ducasse said in the course he did in UPC. The idea is you could throw away your image every day, and start with a fresh new one, EVERY DAY.

One option is fileOuts and fileIns, and in fact, it's simple, reliable and it just works (tm), but you cannot store different versions, and if you did the manual filename juggling, the versions would not have any relationship between them.

Then, here comes monticello. A kind of apt-get + launchpad. It's a package browser and installer (no dependency tracking AFAIK), where repos can be lots of different places, from local directories, to squeaksource remotes, or ftp, or ....

The trick is opening a create a new package (+package button) with the name of the category you want to save. Then, it will appear in the left panel of monticello browser. After that, create a new repository (+Repository button) and add a directory where you want to save it. Then just press the save button.

When you open a new image and want to load the package, open monticello browser, open the repository (+Repository again), click it, and browse. There you'll be able to load the package, and once it's loaded, it will appear in the left panel of the main Monticello Browser.
In the second screenshot you see top left, the different repository types. on the right, the main Monticello screen with the two panels.  My advise is to play a bit with it, selecting and unselecting items to get the feeling of it.

Btw, there's a new project related to source maintaining and versioning called Metacello that seems to be the next iteration of monticello, or "monticello done right", adding full support for package managing, being aware of versions and so.  I'm just guessing as I'm a newbie in both projects and I just skimmed the docs, so please, correct me if I'm wrong.

lunes, 12 de abril de 2010

MP3 fail

Me compré un mp3 y ha ido conmigo a todas partes. Y con él comparto momentos en los que él pone la banda sonora a mis accions, y a las situaciones en las que me veo envuelto.

Es capaz de potenciar una situación, o apartarme del mundo. Un perfecto aliado. Hasta he ido a discotecas a escuchar mi mp3 (HAI TENERIFE). Y a pasear a las 5AM. Me ha hecho conocer gente, y ha dormido en casas ajenas, siempre como una extension mía, como un embajador.

Lo habrán escuchado unas 100 personas distintas.

Me lo compré el 12 de Abril de 2008, lo cargué de música, y no la cambié jamás. A medida que lo escuchaba más y más, me recordaba a cada una de estas 100 personas. Pues el 10 de abril de 2010 dejó de funcionar. Kaput. 2 años menos 2 dias. Con las mismas 2 Gigas.

La pregunta es: Debo llenar mi nuevo mp3 con la misma música?

Portishead, Fat Boy Slim, Michel Camilo, Pearl Jam, Mama ladilla, Janis Joplin, Rare Earth, Ten years after, Zuco 103.

Ya veremos si os vuelvo a ver en mi bolsillo...o os cambio por Mika ;).

Si cambio, una que cae seguro va a ser move to the city.

Parece un cutre-post (y seguramente lo es), pero mi compi de viajes se merece una mencion. ¿no?