Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Question on Grep Function

by kprasanna_79 (Hermit)
on Feb 27, 2009 at 16:44 UTC ( [id://746948]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Revered Monks
I have the following code
@array=('a.b','a'); @result=grep (/\ba\b/,@array); print $_."\n"for(@result);
Result:- a.b a

I need only the word a to be greped from the @array, not a.b.

Any suggestions.
-Prasanna.K

Replies are listed 'Best First'.
Re: Question on Grep Function
by kennethk (Abbot) on Feb 27, 2009 at 17:00 UTC

    You're not using that right. From perlre:

    A word boundary \b is a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W.
    'a' is a word character and '.' is not, so therefore both strings match.
Re: Question on Grep Function
by jettero (Monsignor) on Feb 27, 2009 at 16:55 UTC
    @result = grep {$_ eq "a"} @array;

    UPDATE: Yes, I can see that it differs from m/\ba\z/, they aren't at all similar in appearance. But there's no indication eq "a" isn't what he really wants and it's better in a few ways if that's what he's really looking for. Artist changed the trailing \b to a \z ... those are different too ...

    -Paul

      $_ eq "a" is not the same as /\ba\b/ or even /\ba\z/ and is only correct within the limited number of examples given. It will break when given a string such as 'This is a' which probably should qualify.

      It is of course difficult to guess what the OP exactly wants.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Question on Grep Function
by artist (Parson) on Feb 27, 2009 at 16:53 UTC
    @result=grep (/\ba\z/,@array);
    --Artist

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://746948]
Approved by wfsp
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-23 23:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found