|Just another Perl shrine|
Re: seeking different ways to slice a 2-d arrayby stephen (Priest)
|on Apr 25, 2002 at 03:34 UTC||Need Help??|
A transitory variable is a variable that isn't used for anything other than to schlep data from one line to another. (I'm not sure the term is right, but I think it's what you mean. I call 'em "useless variables", myself.) In other words, if I'm going to say:
Then $foo is a transitory variable. It would be just as simple, and less error-prone, to say:
Why? Because variables can and should vary. It doesn't seem like such a big deal when the assignment and the use of the variable are right next to each other, but what if they get separated?
Oops, on line 2 up there we changed the value of $foo. Also, it makes refactoring harder-- what if you wanted to pull out the stuff inside the if statement into its own subroutine? It'd be simpler if you didn't have $foo there at all, and just called get_foo() when you needed a foo-value.
In your code, @for_data, @map_data, @sort_data, and @grep_data are all transitory variables. Ironically, @last_elements is not... you're using it to collect elements! Nothing wrong with that.
As for why slce_with_sort() and slice_with_grep() aren't doing what you expect, it's because sort and grep don't do what you apparently think they do. :) The block argument to grep is a test block, not a filter block. So the statement
means, "If the item at index 2 of @$_ evaluates to true, return $_." The last bit is important-- it doesn't return the item at index 2, it returns the whole thing. A similar thing is happening with sort. You're sorting each row based on the value of the last column, and returning a list of the rows. Since the values are identical, it doesn't even change their order. :)
So where did you get that water? Sounds like powerful stuff. :)