Nyyr has asked for the wisdom of the Perl Monks concerning the following question:
Its behavior is weird, some db rows get updated, some not. But if I change the $dbh variable names, so that they are different, it works perfectly:use strict; use warnings; ... sub write_status($$$$) { my $dbh = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $result = $dbh->begin_work(); ... $result = $dbh->do("UPDATE results ...."); ... $result = $dbh->commit(); } sub check_apps($\@) { my $dbh = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $sth = $dbh->prepare("SELECT * FROM ...."); ... if (! defined $sth->execute()) { ... } ... write_status($host, $app, $status, $version); } my $dbh = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $sth = $dbh->prepare("SELECT * FROM ...."); ... ... check_apps($host, @processes);
I thought that when I declare a variable in a subroutine with "my", any references to that variable within the subroutine point to the "local" one and all other variables with the same name defined elsewhere are invisible within that subroutine and thus stay untouched by the subroutine. Anyone capable of explaining it to me? :-)use strict; use warnings; ... sub write_status($$$$) { my $dbh_write = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $result = $dbh_write->begin_work(); ... $result = $dbh_write->do("UPDATE results ...."); ... $result = $dbh_write->commit(); } sub check_apps($\@) { my $dbh_apps = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $sth = $dbh_apps->prepare("SELECT * FROM ...."); ... if (! defined $sth->execute()) { ... } ... write_status($host, $app, $status, $version); } my $dbh_main = DBI->connect("DBI:mysql:mysql_socket=" ..... ); ... my $sth = $dbh_main->prepare("SELECT * FROM ...."); ... ... check_apps($host, @processes);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Variable scope & subroutines
by kennethk (Abbot) on Apr 12, 2011 at 14:43 UTC | |
|
Re: Variable scope & subroutines
by ikegami (Patriarch) on Apr 12, 2011 at 14:38 UTC | |
|
Re: Variable scope & subroutines
by InfiniteSilence (Curate) on Apr 12, 2011 at 15:20 UTC | |
by ikegami (Patriarch) on Apr 12, 2011 at 15:27 UTC | |
by InfiniteSilence (Curate) on Apr 12, 2011 at 16:47 UTC | |
by Nyyr (Initiate) on Apr 14, 2011 at 13:44 UTC |