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

Im trying a grep a variable which contains a word ( The word will be updated as the variable is used in a loop) ...

For eg the variable monk contains the following words:- node, post, Perl.

The snippet im using is

if ( grep /$Variable/, <$fh> )

$variable contains the word which i try to find it in the fh which is nothing but files..

The issue is $variable contains the word "node" the following words are getting grepped :- _node similarly for post , _post is also getting matched .. how to find the exact match or how to exclude the "_" in the search...

Replies are listed 'Best First'.
Re: Exact Match - GREP
by tobyink (Canon) on May 13, 2012 at 07:36 UTC

    You might want:

    if (grep /\b$Variable\b/, <$fh>)

    See the definition of \b in perlre under "Assertions".

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Exact Match - GREP
by choroba (Cardinal) on May 13, 2012 at 07:36 UTC
    You can use word boundary \b:
    grep /\b$Variable\b/, <$fh>
Re: Exact Match - GREP
by Mr. Muskrat (Canon) on May 13, 2012 at 13:43 UTC

    In addition to using word boundaries, it looks like you should be reading your line into a scalar before checking against it. You may already be doing this but if so, it's not obvious from the one line you posted.

    Here's a small snippet that works for me. I've included the contents of my test file in __DATA__.

    #!/usr/bin/perl use strict; use warnings; use autodie; open my $fh, '<', '/path/to/your/file'; print "checking against <\$fh> once per \$Variable\n"; for my $Variable ( 'node', 'post', 'Perl' ) { print "$Variable match\n" if ( grep /\b$Variable\b/, <$fh> ); } seek($fh,0,0); # so we can start reading from the beginning again print "\nchecking against each line of <\$fh>\n"; while( my $line = <$fh> ) { for my $Variable ( 'node', 'post', 'Perl' ) { print "$Variable match\n" if ( grep /\b$Variable\b/, $line ); } } __DATA__ node _node post _post Perl _Perl Perl_ __END__ Output: checking against <$fh> once per $Variable node match checking against each line of <$fh> node match post match Perl match