in reply to for-loop issue - swap gets crazy large
If most of the elements in your two-dimensional matrix are known to be zero, then you are dealing with a "sparse matrix" data structure. You're storing certain non-zero values at certain (x,y) coordinates and you're only interested in those, so you only need to store those. Simply search CPAN for the keyword, "sparse."