in reply to Re^2: Multidimentioal array
in thread Multidimentioal array

Hi Monk::Thomas ... I was fooling with these and got a strange result when passing a non-integer to the scripts.

And why do you want to do that?? You are using the user provided value as array indices. Array indices are supposed to be integer values.

If you want to handle non-integer values then you should either implement some method to convert the provided input into a valid value or refuse invalid / strange input.

Replies are listed 'Best First'.
Re^4: Multidimentioal array
by 1nickt (Canon) on Jul 10, 2015 at 11:22 UTC

    And why do you want to do that??

    Um, because I can?

    I am in the habit of testing everything, by which I mean "try to break it". Even small demo scripts for PerlMonks. It's just a habit of mine. Just as I never ever start a script without use strict;. My eyes are too old, my brain is too scattered (running ahead to the next thing while my fingers are still typing) ... too many times I've typed $thing{thang} when I meant $thing->{thang}, and so on and so on.

    So, while I was "fooling" with the version of the script I made for the OP, and yours, I was throwing random values at it, to see what it would do. I threw some large numbers to see how line wrapping would affect it, and then I threw π at it. Of course I knew that such a value would break it: Array indices are supposed to must be integer values, as you point out above, and the matrix would break even if you could somehow pass in a non-integer.

    What I found interesting, and what I drew to your attention since I thought you might also find it interesting, is that the two versions of the script output different values. Neither died nor threw an exception. Since the two versions of the code were almost identical, I found that odd.

    I suspected the for loop, and roboticus very helpfully tracked down in the documentation and explained completely how Perl differs in handling

    my $n = 3.14159; for (my $i=0; $i<$n; $i++)

    and

    my $n = 3.14159; for (0..$n)

    Perhaps you already knew all about this, but I didn't, and I found it interesting, so I shared it.

    Now you know why.

    Remember: Ne dederis in spiritu molere illegitimi!

      Um, because I can?

      Ah. Okay then. Btw. I already did think about adding a sanity check regarding the input value (because I ~never~ trust user input) but decided to leave it out because it would probably only serve to confuse in this case.

      Regarding the different loop behaviour: I did not think about introducing that kind of side effect when I was rewriting the loop. It's something to keep in mind when rewriting code in the future.