miércoles, 29 de julio de 2009

Perl expressiveness for real life

#!/usr/bin/perl

use strict;
use warnings;

my $life;
$life->{'sucks'}= sub { exec 'perl' or die };
$life->{'sucks'}->() ;


Isn't it great that a programming language can express real life feelings in such a readable way?
It doesn't have syntax highlight, but in fact, real life neither.

Let's go back hacking

lunes, 20 de julio de 2009

Se busca pito del sereno (o bien: Fuck0wski somos todos)

Uno ya empieza a hacer tiempo que se afeita, y va viendo como van las cosas.

Y está empezando a hartarse.

"Se busca ingeniero con gran capacidad de aprender, para trabajar en una pequeña empresa en pleno crecimiento en un entorno de contínua evolución."

"Tu cv nos gusta mucho y creemos que cumples el perfil para la plaza que disponemos de tecnólogo especialista en puerros y pepinos."

Joder! Voy a ser responsable de pepinos en una PYME en pleno crecimiento...
Escalabilidad de pepinos? Segundas derivadas del tamaño de un pepino en función de las lineas en premsa?. Espero estar a la altura.

Me voy a la librería más cercana ya que la biblioteca de la universidad esta cerrada en julio (se ve que las vacaciones no son epoca de aprender en este pueblo), y me pillo el de O'Reilly 'Learning Cucumbers' y le hecho un vistazo a 'Cucumbers cookbook' y 'Thinking in cucumbers'.

- Estas dentro chaval. Esto va a marcar un antes y un despues en tu vida profesional. Vas a convertirte en élite. Eso si, empezarás cobrando la cifra que esta justo en la linea de la immoralidad, te parece bien? Por otro lado, en esta empresa somos muy flexibles en lo que respecta a horarios. Sabemos que teneis vida fuera de la empresa, y no queremos que esto
cambie.

"Bueno, aquí voy a aprender un montón", me lanzo a la piscina. El mundo es de los atrevidos. Aunque esto suponga posponer mi emancipación un año más y no poder invitar a cenar a esa chica a la que llevo tiempo detrás. Se la llevará Mindundi, el que empezó la carrera contigo, y se largó a ADE y después hizo un master en siseñorología, y en técnicas de venta y marketing en la red. El que tiene un BMW y no ha pegado sello en su vida. Ese.

Empiezo aprendiendo todo sobre este campo: condiciones idóneas para el deployment de pepinos en clusters no homogéneos, y paralelización de pepinos en grid. Todo se parece bastante a lo que ya conocía, pero ahora estoy al lado de los grandes. Lo que antes hacía en casa, a las 3 de la mañana porque no tenía un duro, ahora lo hago de 9 a 6, y me pagan por ello. Lo mío no eran los pepinos, pero ya me empiezan a gustar.

Chicos, estoy muy contento con vuestro trabajo, nuestros pepinos y nuestros puerros son ya los más reconocidos en europa, aunque aún tenemos que vender nuestra primera partida, esta nuestra empresa ya es referencia europea en venta de pepinos. Sin embargo, hay una pequeña cosita a comentar. Tendríamos que ajustarnos a los calendarios marcados, ya que ahora tendremos responder ante clientes. Se ha acabado la libertad de horarios. Nos ponen una cafetera en el despacho, y nos regalan un cronometro a cada uno, para que contemos los minutos que gastamos meando.

Ya me estoy empezando a cansar de pepinos. El libro de O'Reilly que me compré sigue haciendo de soporte de la pantalla del pc.

Hemos contratado a un comercial que va a dar un nuevo aire en la distribución de nuestros servicios. Efectivamente, veo entrar por la puerta el moreno perfecto de Jorge. Jorge Mindundi.

Ni me cruzo una palabra con él. Pero viene y me comenta toda su vida desde 2003 (última vez que nos vimos). El tio ha estudiado el puto master en cambridge, y se cambió el BMW por un porche boxter, y éste por un audi S3, "porque con el porche todo el mundo te miraba". No quiero esperar a que me cuente sus fiestas en la piscina, y decido largarme con la version informática de "te dejo que tengo la paella al fuego", que viene a ser algo como "uix, voy pallá que ya creo que ya ha acabado de compilar una cosa que tenía ahí..." ..

Todo se empieza a acelerar. Esto significa: a todos nos toca hacer de todo, los proyectos se acaban como buenamente se pueden en un tiempo récord, y la misma presión hace que ni te des cuenta que no estas trabajando en el apasionante mundo de los pepinos, sino que ya estas instalando antivirus y progamando en php. Se acaban haciendo ciertas las grandes frases de Fuckowski:

“Although the current prototype could be technically enhanced, from a
business perspective it fulfils the customer needs”

Que traducido viene a ser:

"Esto se entrega como está, aunque los ingenieros digáis que es una mierda."

Ya me estoy cansando de tantos pepinos. Hace dos días que ya los quito del BigMac.

sábado, 18 de julio de 2009

Getopt::Complete. Making your own tab completions

I just discovered a new perl module in cpan called Getopt::Complete.

As all Getopt::* family, it deals with your program flags. But this module takes it a little further.

Those who know me, know I'm a fan of the DWIM philosophy, so I try to automate every single process in my life. Instead of bash, I use zsh for its amazing DWIMy tab completion.

Well, Getopt::Complete lets you write the tab completion function in perl instead of bash.

Here's a modified example from its perldoc:


#!/usr/bin/perl

use Getopt::Complete (
type => ['names','places','things'], #--type has 3 possible completions
instance => sub {
my ($command, $value, $option, $other_opts) = @_;
if ($other_opts->{type} eq 'names') {
system('touch /tmp/fu');
return [qw/larry moe curly/],
}
elsif ($other_opts->{type} eq 'places') {
return [qw/here there everywhere/],
}
elsif ($other_opts->{type} eq 'things') {
return [ query_database_matching("${value}%") ]
}
elsif ($otper_opts->{type} eq 'surprsing') {
# no defined list: take anything typed
return undef;
}
else {
# invalid type: no matches
return []
}
}
);


to enable the completion, you must tell bash, it should ask the same program to complete words in the commandline.

$complete -C /home/kidd/myapp.pl myapp.pl

Then you should make myapp.pl executable

$chmod +x /home/kidd/myapp.pl

and now, you can start testing it.

WARNING!: In the previous example, I've put an extra line that executes a system call. If you try to tab complete 'myapp.pl --type names --instance ' , the system call will be executed and you'll get a 'free' /tmp/fu file.

That's obviously a serious security issue, but if you use it in a wise way, this module can add some quality to your software requiring only a few lines of code.

TODO: I'm looking at enabling this kind of completion in zsh. If anyone knows it, please leave a comment.

That's all for now.

martes, 14 de julio de 2009

sanfer 2009

vino en la ropa,
cerveza en la copa,
sangre en el suelo
y tu hasta en la sopa.


(perdón por estos sinsentidos)

martes, 7 de julio de 2009

perl arrays and subs. returning arrays of arrays

Now a bit of perl I've been fiddling at $work.

We know that perl flattens lists when passed as arguments to functions (subs) or when we want to return more than one element in a sub. Today I spent 10 minutes remembering how all that worked (c++ is doing nasty things in my brain).

We have some options to avoid the flattening.

sub a { @a = (1,2,1); @b = (4,3,4); [\@a ,\@b]} a; #return a reference (scalar) to an array of arrayrefs.
> [[1,2,1],[4,3,4]]
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)} a; # return a list of two references to arrays. returns the last element by default. see below to access other elems
> [4,3,4]
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)} (a)[0]; #Same, just accessing other elements
> [1,2,1]
sub a { @a = (1,2,1); @b = (4,3,4); [@a ,@b]} a; # returning a reference to an array containing the two arrays flattened into one list.
> [1,2,1,4,3,4]

I like the first option because you can manage all the info in the most flexible way.
Otherwise, if you want to do multiple assignations when returning, you can use the second way like this:
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)}
my ($arr_ref1, $arr_ref2) = a;

And that's it. not really enlightening, but hey, I'm still learning my way to perl :p

domingo, 5 de julio de 2009

keep plaiyng (part 2). End of chapter 3

I've finally found the time to finish chapter 3 of PLAI.

For the moment, the book has introduced only a couple of basic concepts on programming languages, but the fact that's being done all in scheme, gives some cool insights to how variables and basic operations are handled. It's a pretty different approach to the 'classical' one I was taught @ university, where they based everything on c-like languages, and the lexing, parsing and evaluating (compiling there) was done through flex, yacc, and pure c.

The only tricky part of this chapter is getting how to do the parsing and substituting of local vars and fine tunning the scope of those local vars. It's similar to scheme's 'let'.

As we seen in my previous post about PLAI, The basic process of interpreting our pseudo-scheme is based on 3 parts.
define-type: This function allows us to define the different types of elements (primitives, with, and so) in a high abstraction level, just defining the keywords and which elements must have each definition. While defining the WAE structure, we defined num, add, sub and with, all with their structure, and it creates boolean functions called WAE?, add?, sub?...

For example, we can test if a given sexp 'evaluates' to an add:

(add? (add (num 3) (num 2))) ; -> true

parse: This is the process that takes the input, and has to do the sintactical transformations, to make it calc-friendly. This function has to be modified by the 'user' of the book. For the moment, it's been pretty easy to do.


calc: Here is where most action happens. This function is the one which takes an imput (parse's output) and converts it back to scheme, to do the arithmetic (in + and -) or applies substitution on with blocks. Uses the type-case function, so its input has to be coherent with the define-type declared avobe.
(type-case WAE an-ae
(num (n) n)
(add (l r) (+ (calc l) (calc r)))
...
here we see an example of what happens with plain numbers, and 'add'. Given a num, that has one parameter, we just return a number. If the expression we enter is an 'add' one, we just apply recursively the calc function to its args , and finally, we evaluate the (+ arg1 arg2) sexp.

subst: If we encounter a 'with' in the calc function, we have to substitute all subsequent bound-ids to the value of the evaluated bind-expression (with except when we find a nested with binding the same variable id).

This allows us to do things like:
{with {x {+4 3}} {with {y x} y} } ; 7
or even
{with {x {+4 3}} {with {x {+ x 3}} x}} ;10
Well, I think it's enough for now. When I come back from San Fermín party, I'll continue with chapter 4, which introduces the implementation of simple functions.

Thank you for listenning :)

As always, comments, suggestions, kisses, insults... welcome :)