Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete elements from array if they contain some string

Tags:

arrays

perl

Lets say I have an array with following data:

@array[0] = "hello this is a text"
@array[1] = "this is a cat" 
@array[2] = "this is a dog"
@array[3] = "this is a person"
@array[4] = "this is a computer"
@array[5] = "this is a code"
@array[6] = "this is an array"
@array[7] = "this is an element"
@array[8] = "this is a number"

I want to have a loop where it goes through all the array elements and finds out if any of the elements have the value "dog" in them if the element does have dog, then delete the element. and so results would be :

@array[0] = "hello this is a text"
@array[1] = "this is a cat" 
@array[2] = "this is a person"
@array[3] = "this is a computer"
@array[4] = "this is a code"
@array[5] = "this is an array"
@array[6] = "this is an element"
@array[7] = "this is a number"
like image 885
dataminer123 Avatar asked Oct 20 '25 16:10

dataminer123


1 Answers

@array = grep not /dog/, @array;

@array = grep !/dog/, @array;
like image 116
mob Avatar answered Oct 23 '25 07:10

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!