Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if all elements of an array are identical in Perl?

Tags:

arrays

perl

I have an array @test. What's the best way to check if each element of the array is the same string?

I know I can do it with a foreach loop but is there a better way to do this? I checked out the map function but I'm not sure if that's what I need.

like image 882
somebody Avatar asked Feb 21 '10 09:02

somebody


People also ask

How do you check if all array elements are the same?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

What does ~~ mean in Perl?

Just as with the =~ regex match operator, the left side is the "subject" of the match, and the right side is the "pattern" to match against -- whether that be a plain scalar, a regex, an array or hash reference, a code reference, or whatever.

How do you check if an element is in an array Perl?

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

How can you tell if an array has unique elements?

Step 1 − Declare an array and input the array elements at run time. Step 2 − Start traversing the array and check, if the current element is already present in an array or not. Step 3 − If it is already present in an array then, move to the next element in an array and continue.


2 Answers

I think, we can use List::MoreUtils qw(uniq)

my @uniq_array = uniq @array;
my $array_length = @uniq_array;
$array_length == 1 ? return 1 : return 0;
like image 154
Vibhuti Avatar answered Sep 28 '22 06:09

Vibhuti


If the string is known, you can use grep in scalar context:

if (@test == grep { $_ eq $string } @test) {
 # all equal
}

Otherwise, use a hash:

my %string = map { $_, 1 } @test;
if (keys %string == 1) {
 # all equal
}

or a shorter version:

if (keys %{{ map {$_, 1} @test }} == 1) {
 # all equal
}

NOTE: The undefined value behaves like the empty string ("") when used as a string in Perl. Therefore, the checks will return true if the array contains only empty strings and undefs.

Here's a solution that takes this into account:

my $is_equal = 0;
my $string   = $test[0]; # the first element

for my $i (0..$#test) {
    last unless defined $string == defined $test[$i];
    last if defined $test[$i] && $test[$i] ne $string;
    $is_equal = 1 if $i == $#test;
}
like image 21
Eugene Yarmash Avatar answered Sep 28 '22 04:09

Eugene Yarmash