SPUG: Where is grep's return value?
Asim Jalis
asimjalis at acm.org
Tue Sep 10 18:18:35 CDT 2002
On Tue, Sep 10, 2002 at 06:27:32PM -0400, Orr, Chuck (NOC)
wrote:
> I have something that looks like this:
>
> if (grep("$KEY",EXISTING)){
>
> In the event that this is true, I want to print the data that
> makes it true. In other words, I want to print the line from
> EXISTING that contains the pattern from the variable $KEY. The
> problem I am having is figuring out where that line is. Is it
> stored in a variable I don't know about? If not, how can I
> obtain this data? I realize this is a pretty basic question,
> but I am having a tough time finding the answer and I need to
> get this done. Any suggestions/help would be greatly
> appreciated.
The first argument to grep seems wrong. If $KEY contains a
regular expression pattern you should use grep(/$KEY, @EXISTING).
Otherwise Perl will evaluate the string "$KEY" which will
evaluate to true in all cases except when $KEY is 0 or "" or
undefined.
Assuming $KEY contains a regular expression pattern you can print
out all the elements in @EXISTING that match it using:
print join "\n" => grep { /$KEY/ } @EXISTING;
Asim
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Subscriptions; Email to majordomo at pm.org: ACTION LIST EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
For daily traffic, use spug-list for LIST ; for weekly, spug-list-digest
Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org
More information about the spug-list
mailing list