Krish Krish - 3 months ago 8x
Perl Question

Compare 2 set of numbers in Perl

I have 2 scalars as below:

$a = '100 105 010';
$b = '010 105 100';

How do I compare if both has same set of values? order doesn't matter.
one way is to arrange it in ascending order and compare, is there a better way?


You can split each string into an array and compare arrays. By hand:

use warnings;
use strict;

my $x = '100 105 1 010';
my $y = '010 105 100 2';

my @xs = sort { $a <=> $b } split ' ', $x;
my @ys = sort { $a <=> $b } split ' ', $y;

if (@xs != @ys) {
    print "Differ in number of elements.\n";
else {
    for (0..$#xs) {
        print "Differ: $xs[$_] vs $ys[$_]\n" if $xs[$_] != $ys[$_];

# For boolean comparison put it in a sub
print arr_num_eq(\@xs, \@ys), "\n";    
sub arr_num_eq {
    my ($ra, $rb) = @_;
    return 0 if @$ra != @$rb;
    $ra->[$_] != $rb->[$_]  && return 0  for 0..$#$ra; 
    return 1;

The sorting can be moved to the sub as well, which would then take strings. The way it stands it can be used for comparison of existing arrays as well. Please add argument checking.

There is a number of modules that have this capability. The perm from Array::Compare hides the sorting above, but internally joins sorted arrays into strings thus duplicating the work here since we started with strings. The List::AllUtils certainly offers this as well with its long list of utilities. See this post, for example, for a few methods and benchmarks if efficiency is a concern. (Just not the smart match ~~ method.)

What the most suitable method is depends on what this is for and how it is used. Is it only a boolean comparison, or will more be done if they are found to differ? How does it come about in your program flow? Typical sizes of strings, how often is it run? Are the strings most often the same or different, do they differ a lot or a little? Etc.