rsriram has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I am searching through a text file to find out if any elements of the array are present in the line. If found, it has to be printed to a file. I used the following code

for ($x=0; $x <= $#all; $x++) { if($line =~ /@all[$x]/g) { print F2 $line; }

In the output, I get only value of @all[$x]. I need to print the complete line. Can anyone help me out?

Replies are listed 'Best First'.
Re: Searching and printing through a array
by Corion (Patriarch) on Mar 13, 2007 at 09:41 UTC

    I can't reproduce your problem. Your code will print $line many times if more than one element of @all appears in $line. The following code eliminates the loop and replaces it with a single regular expression - maybe you can work from this example or show us data where this example doesn't do what you mean it should:

    #!perl -wl use strict; my @all = qw( rsriram Corion ); my $re = sprintf '\b(?:%s)\b', join "|", map { quotemeta } @all; $re = qr/$re/; print "Searching for $re\n"; for (<DATA>) { chomp; if (/$re/) { print "Found at least one match in '$_'\n"; } else { print "Ignoring '$_'\n"; }; }; __DATA__ This is a line that mentions rsriram. This is a line that mentions Corion. This is a line that mentions Corion and rsriram together. This is a line that mentions neither of the two. This line intentionally left blank.
Re: Searching and printing through a array
by davorg (Chancellor) on Mar 13, 2007 at 09:46 UTC

    Can we see some sample input (both what is in $line and what is in @all). Your method isn't very Perlish, but it should work.

    If you had "use warnings" in your code then you would be warned about using @all[$x] where you almost certainly mean $all[$x]. Also, you're probably better off using a "foreach" loop instead of the C-style loop you have here.

    foreach (@all){ if ($line =~ /$_/) { print F2 $line; } }

    If you're comparing with a lot of lines then you might find it faster to create a regex from all of the elements of @all.

    my $re = join '|', @all; $re = qr/$re/; if ($line =~ /$re/) { print F2 $line; }

    Update: Corion's method of creating a regex is more robust than mine.

Re: Searching and printing through a array
by prasadbabu (Prior) on Mar 13, 2007 at 09:46 UTC

    rsriram,

    Change @all[$x] which is an array slice into $all[$x]which is a individual element in an array. The below is equivalent to your code.

    for my $x (0..$#all) { if($line =~ /$all[$x]/) { print F2 $line; } } simply: foreach (@all) { print F2 $line if $line =~ /$_/; }
    If you show the input and output, it is easy to help you out.
    Also you can do the same using grep and quotemeta.

    Prasad