in reply to Boolean array indexing

johnmillerflorida:

Sometimes altering your data structures can simplify things. Generally, maintaining parallel arrays is the wrong way to store and/or work with your data. If you have related data items, it's usually better to keep it together:

# you originally have two parallel arrays of related data my @a = (6, 7, 8); my @b = (3, 2, 1); # So you need to use artificial means to put the data together, such a +s an index variable for my $index (0 .. $#a) { my ($a,$b) = ($a[$index], $b[$index]); print $a, "\n" if $b>1; } # If instead you keep the related data items together in a two-dimensi +onal array: my @c = ( [6,3], [7,2], [8,1] ); # Then printing the related data is easy, and you needn't track the ar +ray index for my $item (@c) { my ($a,$b) = @$item; print $a, "\n" if $b>1; }

Hopefully the (untested) code above is clear enough. (I need more coffee...)

Another reason to keep the data together is that it can be easier to do some error checking/handling, as you don't have to worry about your arrays being mismatched, etc.

Finally, you may even want to use an array of hashes, so your code can be a little more self-documenting in that you don't have to remember that "slot 0 is a and slot 1 is b":

# An array of hash references can be pretty nice, too: my @c = ( { a=>6, b=>3 }, { a=>7, b=>2 }, { a=>8, b=>1 }, ); # Then printing the related data is easy, and you needn't track the ar +ray index for my $item (@c) { print $item->{a},"\n" if $item->{b}>1; }

...roboticus

When your only tool is a hammer, all problems look like your thumb.