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