Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-19 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found