Search notes:

Perl function: state

With state (and use 5.10.0) it's possible to declare static variables, that is, variables that are initialized only once.
Thus, a function can have its own »state«.
The following example shows a function that every time it is called calculates the average, count, min and max of the numbers passed to the function.
#!/usr/bin/perl
use warnings;
use strict;
use 5.10.0;

min_max_avg(15);
min_max_avg( 5);
min_max_avg( 7);

sub min_max_avg {

  state $min = +"Inf";
  state $max = -"Inf";
  state $sum = 0;
  state $cnt = 0;

  print "  min | max | cnt | avg\n" unless $cnt;

  my $num = shift;

  $sum += $num;
  $cnt ++;

  $min = $num if $num < $min;
  $max = $num if $num > $max;


  printf "  %3d | %3d | %3d | %3d\n", $min, $max, $cnt, $sum/$cnt;

}

# min | max | cnt | avg
#  15 |  15 |   1 |  15
#   5 |  15 |   2 |  10
#   5 |  15 |   3 |   9
Github repository about-perl, path: /functions/state.pl

See also

Perl functions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758207166, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/functions/state(81): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78