You should note that your subroutine here didn't "load" any part of the %list hash into @_ at all; instead you are relying on the fact that somewhere out there is a hash called %list that works how you want it to. As you can imagine, this is not necessarily the safest way to code. You would be better off either making the hash in the subroutine itself (if it's the only thing that uses it) or passing the hash as a parameter (or an element of the hash as a parameter, depending on what is needed) to the sub. This way everything doesn't break if things get moved around or messed with.

Also, as Pancho pointed out, names are important, especially when you're a beginner to help understand what's going on. I imagine the line:

my $list = $list{$animal}

is quite confusing, because you are making a new scalar variable that has the same name ('list') as a hash that you are accessing an element of (meaning you have to use the $ in front of both). This is legal but confusing. Also confusing is that you are calling the scalar $list, when in fact it's not a list at all.

I'm not sure if this is more advice than you bargained for, but do keep it in mind; it will make what's going on more obvious!


I'm a peripheral visionary... I can see into the future, but just way off to the side.


In reply to Re: how do subroutines work by nefigah
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.