Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: seeking different ways to slice a 2-d array

by stephen (Priest)
on Apr 25, 2002 at 03:34 UTC ( #161847=note: print w/ replies, xml ) Need Help??


in reply to seeking different ways to slice a 2-d array

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:

my $foo = get_foo(); do_something($foo);
Then $foo is a transitory variable. It would be just as simple, and less error-prone, to say:
do_something( get_foo() );

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?

my $foo = get_foo(); if ($snargle = 3 && $foo = 2) { whatever($snargle, $foo); # lots of other stuff here... } do_something($foo);

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

grep { $_->[2] } @slice_me;
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. :)

stephen


Comment on Re: seeking different ways to slice a 2-d array
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://161847]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (16)
As of 2015-07-02 16:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (44 votes), past polls