Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: compare two arrays if both are equal and have same elements irrespective of their position

by kcott (Archbishop)
on Jun 18, 2021 at 06:05 UTC ( [id://11133986]=note: print w/replies, xml ) Need Help??


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

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11133986]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-03-28 21:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found