Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

comparing array elements

by Anonymous Monk
on Nov 21, 2003 at 09:20 UTC ( #308827=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks, I wondered if someone could show me a way of comparing each position in two arrays to see if they contain the same value. Is a hash the best way to do this?

Many thanks!

e.g. $array[0] with $array2[0] etc...

Replies are listed 'Best First'.
Re: comparing array elements
by Roger (Parson) on Nov 21, 2003 at 09:42 UTC
    Why complicate the issue with a hash? You can do that (efficiently) with the simplest for loop. :)

    die "arrays different sizes" if $#array1 != $#array2; my $match = 1; # assume arrays match foreach (0..$#array1) { # unless otherwise $match = 0, last if $array1[$_] ne $array2[$_]; } if ($match) { # arrays match .... }
Re: comparing array elements
by BrowserUk (Pope) on Nov 21, 2003 at 10:52 UTC

    If you only need to know if the two arrays are identical, you can cheat a little by using join and eq.

    @a = qw[1 2 3 4 5]; @b = qw[1 2 3 4 5]; @c = qw[1 2 3 4 6]; print "a is equivalent to b" if join("\0", @a) eq join("\0", @b); a is equivalent to b print "a is equivalent to c" if join("\0", @a) eq join("\0", @c);

    This requires that you data doesn't contain nulls, and it will consume a large amount ram (breifly) if the arrays are large.

    However, if you need to know where and/or what the differences are, then there is no avoiding a loop.

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

      Update: I missed the doesn't contain nulls caveat in the previous post. I have no point.
Re: comparing array elements
by Abigail-II (Bishop) on Nov 21, 2003 at 09:25 UTC
    That's a FAQ. perldoc -q intersection.


      Hi Abigail-II, the problem is that intersection works on the whole list, I need to work on individual elements in the same position.
        At first, I thought that too. But then you were considering to use a hash.

        What have you tried so far?


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://308827]
Approved by arthas
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2020-07-07 06:36 GMT
Find Nodes?
    Voting Booth?

    No recent polls found