Today I got something of a slap in the face. Well, at least it made me blush and there is a sting to thinking back on where I might have used a construct like this in a subroutine:

my @list = @_ if @_ > 1;

For the last few months I've been coding away and occasionally using this or something like it. I thought it would always initialise a new lexical and that the assignment was what the condition applied to.

However it seems that in the above case for example, if @_ has 0 or 1 elements, then @list has the value it was assigned the last time the function was called and the condition held true. I just spent the last hour or so going back over my code and breaking this kind of construct into two lines:

my @list; @list = @_ if @_ > 1;

Firstly I just want to caution my fellow monks to be on the lookout for it, as it works the first time and afterward can turn around to bite the naive.

Secondly I'm wondering where this behaviour is clearly explained in the perl docs. I thought that because @list is a lexical, the value could not be there to be picked up on a second invokation of the function. Any pointers or observations on this would be appreciated. Thanks!


In reply to Conditional initialisation by Akhasha

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.