Chaitanyh Singh
Chaitanyh Singh

Reputation: 11

How to grep a pattern for each and every element of an array

I have buffered a complete file in an array soc_data(@soc_data).Now i am trying to grep a pattern in each and every line of the file or we can say each and every element of the array .

i have used this .But this is not working properly and flag is always 1 , but it should toggle as the pattern is not present in every line but only in few lines.

my $flag = 0 ;
if(grep("  ".$val." ".$instance, @soc_data)){
  $flag = 1 ;
}
else {
 $flag = 0 ;
}

Please suggest the way to do it and the mistake that i am doing here .

Upvotes: 0

Views: 346

Answers (2)

mob
mob

Reputation: 118695

grep is often used to apply regular expressions to a list of strings, but the grep in Perl is more general than that, and you must explicitly use a regular expression if that's what you want to use grep for. Compare:

@list = (7,8,9,10);
print grep /1/, @list;        # 10 -- only "10" matches /1/
print grep 1, @list;          # 7 8 9 10, EXPR is always true

Your use of grep is more like the 2nd case. The first argument to grep is just a non-empty and non-zero scalar, so it is always "true" and the return value of grep is always every element in the list. I suspect you want something like

if (grep / $val $instance/, @soc_data) { ... }

or if $val and $instance might have regexp metacharacters,

if (grep / \Q$val\E \Q$instance\E/, @soc_data) { ... }

(I don't really know what you mean by "toggling", so I probably haven't properly addressed that part of your question)

Upvotes: 1

simbabque
simbabque

Reputation: 54381

It cannot toggle with the code you have written. Your code checks if there is any occurrence of the pattern in the array. grep will look at each line (element in the array) in turn, and return a list of the ones that match the pattern. Then your flag is set and you are done.

my @list = ( 1 .. 20 );
my @match = grep /3/, @list;
print "@match";

# 3 13

If you want to do each line individually, you need to loop over the array yourself in an outer loop, and then do a match. No need for grep then.

foreach my $line (@soc_data) {
    my $flag = 0;
    $flag = 1 if $line =~ m/  $val $instance/; # you might want to use \s

    # do things with $flag
}

Upvotes: 5

Related Questions