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.
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.
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.
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.
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.
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;
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 undef
ined 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 undef
s.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With