http://qs321.pair.com?node_id=675684


in reply to how do subroutines work

The explanations given are correct. To elaborate on nefigah's point you will often find data structures which logically belong inside a subroutine defined outside. That is because if it is defined inside the subroutine the variable has to be initialized every time the subroutine is called. Unfortunately you can't just stick the variable next to the subroutine as the variable must be initialized before the subroutine is called.

eval { print speak('sheep'), "\n"; }; print $@ if $@; my %says = ( sheep => 'baa', monkey => 'foo', ); eval { print speak('monkey'), "\n"; }; print $@ if $@; sub speak { my $animal = shift; die unless defined $says{$animal}; return $says{$animal}; } __END__ Died at Perl-1.pl line 21. foo
Placing that data structure before calling speak in the example is a bad practice, it spacially separates things that are related and gives wide access to a data structure that is private to a subroutine.

Perl 5.10 has state variables for just this purpose, they are initialized only on the first time a function is called.

use 5.010_000; eval { say speak('sheep'); }; print $@ if $@; eval { say speak('monkey'); }; print $@ if $@; sub speak { my $animal = shift; state $says = { sheep => 'baa', monkey => 'foo', }; die unless defined $says->{$animal}; return $says->{$animal}; } __END__ baa foo
Note that state variables can only be scalars (at least at 5.10.0) and I've had to change %says = () to $says = {}. I also get to use say ... instead of print ..., "\n"

If you have to do this in earlier versions then wrap the data structure and sub routine in a BEGIN block so the data is initialized during compilation.

BEGIN { my %says = ( sheep => 'baa', monkey => 'foo', ); sub speak { my $animal = shift; die unless defined $says{$animal}; return $says{$animal}; } }
If initializing the data is expensive and you may not need it or you can't initialize it at compile time then you can do
{ my $says; sub speak { my $animal = shift; $says |= initialize_says(); die unless defined $says->{$animal}; return $says->{$animal}; } }
$says will only be initialized if it is not already initialized. If available state is much cleaner;)
sub speak { my $animal = shift; state $says = initialize_says(); die unless defined $says->{$animal}; return $says->{$animal}; }