Conditional match similar to IDL's where function

V

vorticitywolfe

Hello,

I'm been trying to produce a result similar to IDL's where
function...that returns the indices of where a condition is true.

For example:
@array=(2,4,7,9,10,16,20,82);
print where(@array < 20 and @array >= 10);

this should print 4,5 indicating that at index 4 and index 5 this
condition is true.

previous posts always match if something exists in a string, I want to
mathematically check a condition
"What are the indices of elements that match?", you'll need something like
@indices = grep $array[$_]=~/something/, 0..$#array;

Do you have any ideas for me?

Thanks for the help!

Jonathan
 
T

Tad J McClellan

Hello,

I'm been trying to produce a result similar to IDL's where
function...that returns the indices of where a condition is true.

For example:
@array=(2,4,7,9,10,16,20,82);
print where(@array < 20 and @array >= 10);

this should print 4,5 indicating that at index 4 and index 5 this
condition is true.

previous posts always match if something exists in a string, I want to
mathematically check a condition


You want to use arithmetic operators rather then the pattern match operator.

"What are the indices of elements that match?", you'll need something like
@indices = grep $array[$_]=~/something/, 0..$#array;

Do you have any ideas for me?


perldoc -f grep

says:

grep BLOCK LIST
grep EXPR,LIST

The code you quoted above uses the EXPR form.

Simple replace the pattern match EXPR with an arithmetic EXPR:

@indices = grep $array[$_] < 20 && $array[$_] >= 10, 0..$#array;

I would prefer the BLOCK form for this instead though:

@indices = grep {$array[$_] < 20 and $array[$_] >= 10} 0..$#array;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top