water has asked for the wisdom of the Perl Monks concerning the following question:

The Class::DBI docs include the following suggestion for wrapping txns:
sub do_transaction { my $class = shift; my ( $code ) = @_; # Turn off AutoCommit for this scope. # A commit will occur at the exit of this block automa +tically, # when the local AutoCommit goes out of scope. local $class->db_Main->{ AutoCommit }; # Execute the required code inside the transaction. eval { $code->() }; if ( $@ ) { my $commit_error = $@; eval { $class->dbi_rollback }; # might also di +e! die $commit_error; } }
Can some explain this line
local $class->db_Main->{ AutoCommit };
Is this a set statement? The DBI docs mention setting
$dbh->{AutoCommit} = 0
to turn on txns, but clearly the local statement in the routine above doesn't have the =0. What is this  local statement doing?

Thanks

water

Replies are listed 'Best First'.
Re: Seeking clarification on 'local' in Class::DBI txn code
by etcshadow (Priest) on Mar 21, 2004 at 21:24 UTC
    Short answer: localing a value implicitly undefines it. Thus, you can think of this as doing:
    local $class->db_Main->{ AutoCommit }; $class->db_Main->{ AutoCommit } = undef;
    And, since autocommit is used as a boolean value, undef is treated in the same manner as zero, so it's like setting it to zero.

    Personally, I like to be explicit about such things, so I would say

    local $class->db_Main->{ AutoCommit } = 0
    But that's just me. It's not necessary for any purpose other than to avoid having someone ask this question. In my opinion, though, that's a worthwhile reason to do it.
    ------------ :Wq Not an editor command: Wq
perldoc -f local
by Anonymous Monk on Mar 21, 2004 at 14:12 UTC
    perldoc -f local

      perldoc -f local

      That doesn't answer the OP's question.
      Interestingly though, in the OP's code there are three lines of useful documentation telling us what it does.
      The question that still needs to be answered is Why does it do it without explicitly setting it to = 0;

      Update:
      The answer is to be found more than just a little below the surface of   perldoc DBI   where it says:

      Also note that in this older form of "connect", the "$dbh->{AutoCommit}" attribute is undefined

      Still not that obvious.

      Sören

        perldoc -f local refers you to perldoc perlsub for details, where it says "If no initializer is given for a particular variable, it is created with an undefined value."