State variables are just like my variables but with a different lifetime,
so it is safe (assuming it would be safe to use my variables that life for
the lifetime of the program). In this case, what happens if you lose
database access and then reconnect? What happens if you have two database
handles? Your statement handles are going to be bad or refer to the wrong
DB. What you really want here is the $dbh->prepare_cached method call. It
will correctly handle both scenarios and avoid reparsing the SQL.

On Mon, Apr 24, 2017, 20:02 lee <l...@yagibdah.de> wrote:

> Hi,
>
> is it ok to assign an object to a state variable?  Or does doing so
> involve a chance of causing problems because objects are not supposed or
> designed to be used with the state-feature?
>
> Example:
>
>
> use feature qw(state);
> use DBI;
>
>
> sub foo {
>   my ($dbh, $q, $finish) = @_;
>
>   state $sth = $dbh->prepare("SELECT foo FROM bar WHERE baz = ? LIMIT 1");
>   if($finish) {
>     $sth->finish();
>     return 0;
>   }
>
>   $sth->execute($q);
>   my ($ret) = $dbh->selectrow_array($sth);
>
>   return $ret;
> }
>
>
> #
> # do some stuff like connecting to database etc.
> #
>
> foreach (1..10) {
>   my $z = foo($dbh, $_, 0);
>   #
>   # do more stuff with $z
>   #
>   my $x = foo($dbh, $z, 0);
>   #
>   # ...
>   #
> }
>
> foo($dbh, 1);
> exit 0;
>
>
> I think it would be nicer to keep statement handles ($sth) contained within
> the functions that use them instead of defining them in the main part and
> handing them over to the functions.  Their very purpose is that you define
> a handle once and use it multiple times, thus saving the overhead of
> interpreting the statement every time it is used.
>
> But can I safely use a state-variable like this?  If not, then what?
>
>
> --
> "Didn't work" is an error.
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
>

Reply via email to