Here's another approach:

my @array_one = (2, 1, 3, 5); my @array_two = (2, 3, 1, 0); my %indices; for my $i (0..3) { # store at which index the elements occurred push @{$indices{$array_one[$i]}}, $i; push @{$indices{$array_two[$i]}}, $i; } my ($same_pos, $diff_pos) = (0, 0); for my $val (sort keys %indices) { my $i = $indices{$val}; if (@$i >= 2) { if ($i->[0] == $i->[1]) { $same_pos++; print "element '$val' in same position\n"; } else { $diff_pos++; print "element '$val' in different position\n"; } } } printf "=> %d element%s in same position, %d element%s in different po +sition\n", $same_pos, $same_pos==1 ? "":"s", $diff_pos, $diff_pos==1 ? "":"s";

Output:

element '1' in different position element '2' in same position element '3' in different position => 1 element in same position, 2 elements in different position

Note that this assumes that an element occurs in either the same or in a different position, but not both (and that there's no more than one occurrence of each element within one array). I.e. something like this

3, 1, 3, 5 3, 3, 1, 0

will produce ambiguous output (report the first occurrence, that is).


In reply to Re: Array compare by almut
in thread Array compare by plink

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.