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.


In reply to Re: Boolean array indexing by roboticus
in thread Boolean array indexing by johnmillerflorida

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.