Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: how do subroutines work

by hipowls (Curate)
on Mar 22, 2008 at 21:24 UTC ( #675684=note: print w/replies, xml ) Need Help??

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 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}; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://675684]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2020-09-22 18:07 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (129 votes). Check out past polls.