[Melbourne-pm] Closures and scope warnings
Toby Corkindale
toby.corkindale at strategicdata.com.au
Tue Jul 27 20:48:34 PDT 2010
On 28/07/10 13:34, Jacinta Richardson wrote:
> Toby Corkindale wrote:
>> Hmm,
>> here's something that caught me out.. probably because it's not great
>> practice. (But it is a common theme in using DBIx::Class transactions)
>>
>> my $thing;
>> sub { my $thing = 'wibble' }->();
>
> This isn't just constrained to this circumstance, and is probably
> normally considered a feature. Consider:
>
> my $name = "Jacinta";
>
> print_name($name);
>
> #### much later
>
> sub name {
> my $name = shift;
>
> print "$name\n";
> return;
> }
>
>
> Would you *really* want every subroutine which creates variables which
> shadow top-level variables to warn about such? I don't think Perl
> distinguishes between your case and mine.
No, but when the anonymous sub is used like a sort of single-use
closure, like this?
sub do_something {
my $schema; #isa DBIx::Class::Schema
my $user = $schema->resultset('Users')->find(1);
my $new_role = "something";
my $old_role;
$schema->txn_do(sub {
$user->name("flooble");
$old_role = $user->role; # <-- accessing data outside
$user->add_role($new_role); # <-- and again
$user->update;
});
}
That's the "best practice" way to do transactions, I believe, but it
does use a closure in a way that it wasn't really intended, I think?
More information about the Melbourne-pm
mailing list