To check if two arrays are equal in Perl, you can use the cmp
operator for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
@arr1
and @arr2
with the same elements.cmp
operator to check if the arrays are equal and store the result in the variable $equal1
.cmp
operator checks if two arrays have the same elements in the same order.$equal1
to the console.@arr1 = (1, 2, 3);
@arr2 = (1, 2, 3);
$equal1 = (@arr1 cmp @arr2) == 0;
print "Arrays are equal: $equal1\n";
Arrays are equal: 1
In this example,
@arr3
and @arr4
with different elements.$equal2
.$equal2
is set to true
; otherwise, it's set to false
.$equal2
to the console.@arr3 = (1, 2, 3);
@arr4 = (3, 2, 1);
$equal2 = 1;
for my $i (0 .. $#arr3) {
if ($arr3[$i] != $arr4[$i]) {
$equal2 = 0;
last;
}
}
print "Arrays are equal: $equal2\n";
Arrays are equal: 0
In this tutorial, we learned How to check if Two Arrays are Equal in Perl language with well detailed examples.