perlarrays

How can I check if all elements of an array are identical in 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.


Solution

  • 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;
    }