Search⌘ K
AI Features

State vs Closures and Pseudo-State

Explore the differences between state variables and closures in Perl functions. Understand how state variables maintain values between calls and why pseudo-state techniques are deprecated. This lesson helps you write cleaner, more idiomatic Perl code by using closures and state effectively to manage function state.

State vs. closure

Closures use lexical scope to control access to lexical variables, even with named functions:

Perl
{
my $safety = 0;
sub enable_safety { $safety = 1 }
sub disable_safety { $safety = 0 }
sub do_something_awesome {
return if $safety;
say "Keep learning with Educative";
}
enable_safety();
do_something_awesome();
disable_safety();
do_something_awesome();
}

All three functions encapsulate that shared state without exposing the lexical variable outside their shared scope. This idiom works well for cases where multiple functions access that lexical, but it’s clunky when only one function does.

Use state variables

...