in reply to Boolean array indexing
In this specific case, I would probably go for a single map such as the solution proposed by linuxer. However, building on your own solution, I would like to point out that you don't need an intermediary array @ind if you just pipeline the grep and the map, as shown in the following Perl debugger session:
Again, in this specific case, I would probably do everything in one map, as in the solution proposed by linuxer, but the possibility of pipelining various list operators as above can be a very powerful tool. This is an example of the same idea on the same problem, using two more list operators:DB<1> @a = ( 6,7,8 ); DB<2> @b = ( 3,2,1 ); DB<3> @c = map {$a[$_]} grep {$b[$_] > 1} 0..$#b; DB<4> p "@c"; 6 7 DB<5>
To understand this type of command pipeline, it has to be read from right to left ( and from bottom to top if it is spread on several lines). Well known examples of such constructs are the Schwartzian Transform and variations thereon such as the Guttman-Rosler Transform for efficiently sorting data.DB<5> print join " ; ", map {$a[$_]} grep {$b[$_] > 1} 0..$#b; 6 ; 7 DB<6>
Update: When I started to type this, there was only linuxer's answer. Then, while I was typing the above, my daughter came twice to ask me something, so that it took me 20 or 25 minutes to finish typing the above, and many good answers were delivered in between, so that the above is less useful. Alright, fair enough, you have to be fast if you want to be the first. ;-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Boolean array indexing
by johnmillerflorida (Initiate) on Nov 21, 2013 at 23:19 UTC |