To check if a specified element is present in an array in Perl, you can use methods like grep
or a loop to iterate through the array and check each element.
In this example,
@numbers
with values 10, 20, 30, 40, 50.grep
function to check if element 30 is present in the array.grep
function returns a list of elements that match the condition, which we check for emptiness to determine if the element is present.@numbers = (10, 20, 30, 40, 50);
element = 30;
@found_elements = grep { $_ == $element } @numbers;
$is_present = @found_elements ? 'true' : 'false';
print "Element 30 is present: $is_present\n";
Element 30 is present: true
In this example,
@fruits
with values 'apple', 'banana', 'cherry'.foreach
loop to iterate through the array and check each element with the specified element 'banana'.$found
to true; otherwise, it remains false.@fruits = ('apple', 'banana', 'cherry');
element = 'banana';
$found = 0;
foreach $fruit (@fruits) {
if ($fruit eq $element) {
$found = 1;
last;
}
}
$is_present = $found ? 'true' : 'false';
print "Element 'banana' is present: $is_present\n";
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in Perl language with well detailed examples.