in reply to Re: Boolean array indexing
in thread Boolean array indexing

Thank you very much, linuxer, this is indeed one line :-)

Still, is there no built-in function in perl which returns the indices of an array based on a boolean query?

I am moving to perl from matlab (don't want to get into fights about which programming languages are the best (or whether matlab can be considered as one in the first place ;-)), but I think matlab has an edge here, since the equivalent matlab code would be:

a=a(find(b>1))

Replies are listed 'Best First'.
Re^3: Boolean array indexing
by hdb (Monsignor) on Nov 21, 2013 at 22:38 UTC

    List::MoreUtils has a function indexes which does that:

    indexes BLOCK LIST
    Evaluates BLOCK for each element in LIST (assigned to $_) and returns a list of the indices of those elements for which BLOCK returned a true value. This is just like grep only that it returns indices instead of values:

    @x = indexes { $_ % 2 == 0 } (1..10);   # returns 1, 3, 5, 7, 9

    So you could write

    @a[ indexes { $_ > 1 } @b ]

    Not quite as nice as in Matlab but close.

Re^3: Boolean array indexing
by GrandFather (Saint) on Nov 21, 2013 at 22:35 UTC

    matlab is a special purpose tool tuned for handling arrays. Perl is much more a general purpose scripting language. It is unsurprising that there are elegant ways of performing tasks within matlab problem domain that Perl can't directly match. There are many things that Perl does nicely for which matlab has no equivalent. Ya pays ya money (a lot of money in the case of matlab if you're not in an educational institution) and takes ya choice.

    True laziness is hard work
Re^3: Boolean array indexing
by hdb (Monsignor) on Nov 21, 2013 at 22:49 UTC

    I had a number of projects in the past where I used Perl to create input files for Matlab, mainly matrices, and then kicked off Matlab to do the processing of those, and then back in Perl created nice reports to present the results (LaTeX files). Using multiple tools (if available) can be very efficient, using each for what it is best for.