To check if two arrays have the same elements regardless of order in Perl, you can sort both arrays and then compare them element by element.
In this example,
@arr1
and @arr2
with the same elements but in different order.sort
function.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result.@arr1 = (1, 2, 3);
@arr2 = (3, 1, 2);
sub arrays_equal {
my ($arr1, $arr2) = @_;
return 0 unless @$arr1 == @$arr2;
for my $i (0 .. $#$arr1) {
return 0 unless $arr1->[$i] == $arr2->[$i];
}
return 1;
}
print arrays_equal([sort @arr1], [sort @arr2]);
1
In this example,
@arr3
and @arr4
with different elements.sort
function.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result.@arr3 = (1, 2, 3);
@arr4 = (4, 5, 6);
sub arrays_equal {
my ($arr1, $arr2) = @_;
return 0 unless @$arr1 == @$arr2;
for my $i (0 .. $#$arr1) {
return 0 unless $arr1->[$i] == $arr2->[$i];
}
return 1;
}
print arrays_equal([sort @arr3], [sort @arr4]);
0
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Perl language with well detailed examples.