in reply to compare two arrays if both are equal and have same elements irrespective of their position

G'day noviceuser,

Based on the simplicity of your example arrays, and your subsequent "No, i have just started out perl sometimes back. Any regular way will work", you might be interested in this basic solution that doesn't employ modules.

#!/usr/bin/env perl use strict; use warnings; my @data = ( [[qw{a b}], [qw{a b}]], [[qw{a b}], [qw{a}]], [[qw{a b}], [qw{a b c}]], [[qw{a b}], [qw{b 99 xyz}]], ); for (@data) { my @ref = @{$_->[0]}; my @test = @{$_->[1]}; print "REF: '@ref' TEST: '@test'\n"; my ($only_in_ref, $not_in_ref) = compare(\@ref, \@test); print "Only in REF: @{[sort keys %$only_in_ref]}\n"; print "Not in REF: @{[sort keys %$not_in_ref]}\n"; print '-' x 40, "\n"; } sub compare { my ($ref, $test) = @_; my %only_in_ref = map +($_ => 1), @$ref; my %not_in_ref; for (@$test) { if (exists $only_in_ref{$_}) { delete $only_in_ref{$_}; } else { ++$not_in_ref{$_}; } } return (\%only_in_ref, \%not_in_ref); }

Output:

REF: 'a b' TEST: 'a b' Only in REF: Not in REF: ---------------------------------------- REF: 'a b' TEST: 'a' Only in REF: b Not in REF: ---------------------------------------- REF: 'a b' TEST: 'a b c' Only in REF: Not in REF: c ---------------------------------------- REF: 'a b' TEST: 'b 99 xyz' Only in REF: a Not in REF: 99 xyz ----------------------------------------

— Ken

  • Comment on Re: compare two arrays if both are equal and have same elements irrespective of their position
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: compare two arrays if both are equal and have same elements irrespective of their position
by hippo (Archbishop) on Jun 18, 2021 at 09:07 UTC