4

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"
1
  • 4
    @var[index] = ... is bad style. Use $var[index] = .... This expression uses the $ sigil, but still refers to the named array @var. See perldata. Commented Jun 20, 2013 at 15:17

3 Answers 3

14

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

@array = grep !/dog/, @array;
Sign up to request clarification or add additional context in comments.

2 Comments

v5.16.3 gives me a error "not enough arguments for grep" The "not" should be a "!" perhaps? (Another answer is using !)
Sorry David, not has different precedence than !
9

Clearly just reassigning the whole array is easier, but to actually loop through and delete, you do something like this:

use strict;
use warnings;

my @array = (
    'hello this is a text',
    'this is a cat',
    'this is a dog',
    'this is a person',
    'this is a computer',
    'this is a code',
    'this is an array',
    'this is an element',
    'this is a number'
);

for my $index (reverse 0..$#array) {
    if ( $array[$index] =~ /dog/ ) {
        splice(@array, $index, 1, ());
    }
}

print "$_\n" for @array;

output:

hello this is a text
this is a cat
this is a person
this is a computer
this is a code
this is an array
this is an element
this is a number

1 Comment

$#array is the index of the last element of @array (or -1 if it is empty)
8
@array = grep(!/dog/, @array);

2 Comments

does this delete the element also?
Yes. You could print the elements (or element counts) before and after this operation to see the difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.