I have an array with the following values:
push @fruitArray, "apple|0";
push @fruitArray, "apple|1";
push @fruitArray, "pear|0";
push @fruitArray, "pear|0";
I want to find out if the string "apple" exists in this array (ignoring the "|0" "|1")
I am using:
$fruit = 'apple';
if( $fruit ~~ @fruitArray ){ print "I found apple"; }
Which isn't working.
Don't use smart matching. It never worked properly for a number of reasons and it is now marked as experimental
In this case you can use grep
instead, together with an appropriate regex pattern
This program tests every element of @fruitArray
to see if it starts with the letters in $fruit
followed by a pipe character |
. grep
returns the number of elements that matched the pattern, which is a true value if at least one matched
my @fruitArray = qw/ apple|0 apple|1 pear|0 pear|0 /;
my $fruit = 'apple';
print "I found $fruit\n" if grep /^$fruit\|/, @fruitArray;
I found apple
I - like @Borodin suggests, too - would simply use grep()
:
$fruit = 'apple';
if (grep(/^\Q$fruit\E\|/, @fruitArray)) { print "I found apple"; }
which outputs:
I found apple
\Q...\E
converts your string into a regex pattern.|
prevents finding a fruit whose name starts with the name of the fruit for which you are looking.Simple and effective... :-)
Update: to remove elements from array:
$fruit = 'apple';
@fruitsArrayWithoutApples = grep ! /^\Q$fruit\E|/, @fruitArray;
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