in reply to Re^2: The weirdest problem with undef
in thread The weirdest problem with undef

I assume you're saying that because you're accessing the data again in "scan_matrix". So here's what's really happening.

  1. Each time round the loop new lexical variables are created by the "my" call.
  2. You then call "get_elements" which puts data into the _package_ variables called @source and @destination, _not_ the lexical variables that you have created.
  3. You then call "scan_matrix" which also accesses the _package_ variable versions.
  4. You then use "undef" in your main loop which effects the _lexical_ versions of the variables.
  5. The loop ends and your lexical variables go out of scope and are destroyed. The package variables, however, still exist and still contain the data that "get_elements" put in them.
  6. The loop executes again and the process repeats.
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^4: The weirdest problem with undef
by insaniac (Friar) on Dec 22, 2004 at 10:26 UTC
    dave, many thanks for this clarification... i obviously made a big mistake! i'll test it now...
    --
    to ask a question is a moment of shame
    to remain ignorant is a lifelong shame
      EVERYBODY: thanks for your replies, i changed the my (@source,@destination) into local (@source,@destination) and now it works like it should.

      so thanks again for this simple lesson..
      --
      to ask a question is a moment of shame
      to remain ignorant is a lifelong shame

        See, that's exactly the quick hacky fix that I'd deliberately _not_ given you.

        Please do it the right way. Pass the lexical variables into the subroutines. There's rarely a good reason to use package variables.

        And please use "strict" and "warnings". It'll make it much easier to catch bugs like this in the future.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

        But this still isn't doing what you are expecting. Not declaring those two variables would produce the same result (given the amount of code you have given). A local block is making a local copy of those global variables for use inside the block, but you are altering and accessing both variables outside of the block... It may behave as you expect, but it isn't doing what you think it is.

        Update: When I said copy, I didn't mean the global values are retained. Wrong use of the word. I meant 'reset for use inside of the block.'

        Ouch! While there are indeed (at least) Seven Useful Uses of local, IMHO there are tons of better WTDI.

        Honestly I can hardly imagine how you could devise such a byzantine scheme where parameter passing into the subs would be the most natural choice...