Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl searching for string contained in array

Tags:

perl

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.

like image 533
Jaron787 Avatar asked Mar 13 '23 15:03

Jaron787


2 Answers

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;

output

I found apple
like image 187
Borodin Avatar answered Mar 16 '23 00:03

Borodin


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.
  • Looking for the | 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;
like image 40
MarcoS Avatar answered Mar 15 '23 23:03

MarcoS