walker
walker

Reputation: 13

how to remove items from an perl array based using grep and shift?

I need to remove the data record symbol and any blank lines in a dataRecord using perl.

for example,

$/ = "__Data__"

__Data__
riririririr
djkfkdfjkdjkf
dghghghghghghg
(blank line)

     my @dataRecord = split(/\n/);
     grep(/(__Data__|/,@dataRecord);

How do I remove the items I do not want in the array based on the grep filtering?

Upvotes: 1

Views: 8646

Answers (3)

gpojd
gpojd

Reputation: 23085

This should work:

my @filered_list = grep { length( $_ ) and $_ ne '__Data__' } @dataRecord;

Upvotes: 3

Zaid
Zaid

Reputation: 37156

Not sure what's going on with the input record separator here, and the use of split is not valid unless the implicit $_ is being used.


To answer the question though, use the ! operator to negate the sense of the match:

@dataRecord = grep { ! /__Data__|^$/ } @dataRecord;

The ! can also be replaced with not for this case:

@dataRecord = grep { not /__Data__|^$/ } @dataRecord;

Upvotes: 3

Diego Sevilla
Diego Sevilla

Reputation: 29019

Well, if you want the elements that match the criteria:

@dataRecord = grep(/expr/,@dataRecord);

(assuming that the elements that you don't want in the array are the ones that don't pass the matching regex).

Upvotes: 0

Related Questions