basics intermediate

How to use the state keyword in Perl

Question

What is the state keyword in Perl and how does it differ from my?

The state keyword (Perl 5.10+) declares a lexical variable that persists between function calls, similar to static variables in C:

use v5.10;
use strict;
use warnings;

sub counter {
    state $count = 0;  # Initialized only once
    $count++;
    return $count;
}

say counter();  # 1
say counter();  # 2
say counter();  # 3

# Compare with 'my' (reinitialized each time)
sub broken_counter {
    my $count = 0;
    $count++;
    return $count;
}

say broken_counter();  # 1
say broken_counter();  # 1
say broken_counter();  # 1

Use state when you need a variable to remember its value between function calls without using global variables.

Was this helpful?

Related Questions