Ruby like code blocks in Perl
While thinking about how to best define migrations/tables in my experimental module Forward::ORM, I realized that I might need Ruby like code blocks to keep certain things in scope:
In my first version, I used default Perl:
sub up {
my $self = shift;
$self->create_table('authors', sub {my $t = shift;
$t->add_column('id', 'integer', primary_key => 1);
$t->add_column('name', 'varchar', length => 40);
});
}
I then noticed that Method::Signatures::Simple also works with anonymous functions and methods, so my code now looks like this:
sub up {
my $self = shift;
$self->create_table('authors', func($t){
$t->add_column('id', 'integer', primary_key => 1);
$t->add_column('name', 'varchar', length => 40);
});
}
and later
$code_ref->($table);
While not as pretty as Ruby code blocks, as func has to be passed as a parameter and thus must be surrounded by braces, it is at least a small improvement.
Rather than passing the object to the subroutine, why not place it into $_
sub up {
my $self = shift;
$self->create_table(authors => sub {
$_->add_column(...);
$_->add_column(...);
});
}
okay, this would also be possible, but like a named parameter more (it is more obvious that $t or $table is the table object, which might be easier to explain to end users)
You could do both $_ and the named param :)