The issue that you are fighting is locality of reference. Locality of reference means that any given variable is localized as much as possible to a small section of code. See Pass by reference vs globals or RE (tilly) 3: redeclaring variables with 'my' for my attempts to explain why this matters.

The iron-clad rule is just a rule that improves locality of reference. But the rule doesn't start or end there. For instance the other day I had an array of colours that I needed to synchronize between a table and a graph. Now I could easily export the array I used in my graph to the table and it would work. But that wouldn't preserve locality of reference, someone else might do something stupid like put in code somewhere that set that array making it hard to figure out why the colors did not synchronize properly.

So I wrote a function in the graph code that returned a closure which would take in elements going into the table and return them with the appropriate color tag. Much better! Inside the graph code you can see that nobody else is abusing this array. Inside the function there is hidden state, but that is documented and the table code knows all of the calls to that function. (Why didn't I return the array? Because if you run out of colors you cycle, and I found that implementing that bit of internal logic in the table to not be very nice. Besides which, some day that behaviour might change, and it would be good that I have it localized!)

So I had an example where I wrote almost exactly what you wrote above. Which breaks the rule that people learn. But by breaking the rule I believe I managed to achieve the goal of the naive rule...


In reply to Re (tilly) 3: problem with variable values by tilly
in thread problem with variable values by Anonymous Monk

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.