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


In reply to Re: how do subroutines work by hipowls
in thread how do subroutines work by baxy77bax

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.