[Dbix-class] Q: txn_do() w/ or w/o closure
Rob Kinyon
rob.kinyon at gmail.com
Thu Apr 8 12:44:33 GMT 2010
On Thu, Apr 8, 2010 at 07:45, Bernhard Graf <dbic4 at augensalat.de> wrote:
> Here are two ways of doing the same thing with txn_do():
>
> my $author = $schema->resultset('Author');
> my @titles = qw/Night Day It/;
>
> # 1: giving a closure to txn_do()
> $schema->txn_do(
> sub {
> $author->create_related('books', {
> title => $_
> }) for @titles;
> };
> );
>
> # 2: giving a code ref together with all external variables
> $rs = $schema->txn_do(
> sub {
> my ($author, $titles) = @_;
> $author->create_related('books', {
> title => $_
> }) for @$titles;
> }, $author, \@titles
> );
>
> Does it make any difference?
> Is there a recommended way of doing it (better use or avoid closure)?
First off, there is almost never a reason to avoid closures. Closures
aren't the boogeyman. Not even for parallelizing.
The main reason I can see to use the second form is so that you can
have a named subroutine. So, instead of:
$schema->txn_do( sub {
my ($x, $y) = @_;
...
}, $some_x, $some_y );
You would do:
sub do_x_with_y {
my ($x, $y) = @_;
...
}
# Elsewhere...
$schema->txn_do( \&do_x_with_y, $some_x, $some_y );
Rob
More information about the DBIx-Class
mailing list