* Umesh T G <[EMAIL PROTECTED]> [2006-05-19T08:54:17]
> I am trying to grep a variable from a scalar value. Here is the example 
> below.
> 
> $var = "mydisk";
> $line = "mydisk is bad";
> if (grep/\$var/,$line) {
>    print "disk is not bad";
> }

The simplest answer, already given, is that you should lose the backslash
before the $ in $var, but I think that's not helpful enough.

You're using the "grep EXPR, LIST" form of grep, which evaluates an expression
for each element of the LIST and returns either the number of things for which
it was true, or those things for which it was true.  I suggest never using this
form.  Instead, use the "grep BLOCK LIST" form, which replaces that expression
with a little snippet of code.  This is more flexible and often clearer.

You could rewrite your line as:  if (grep { /$var/ } $line) {

Then again, since $var isn't a regular expression, you could just check whether
the contents of $var occur in $line:

  if (grep { index($_, $var) > -1 } $line) {

That says, "if any of the given elements have the contents of $var in them
somewhere..."  That way you can avoid using the regular expression engine,
which might be slower or do things you didn't expect, depending on the contents
of $var.

Then again, since you're only using one thing, not a list, you could skip grep
entirely!

  if (index($line, $var) > -1) {

-- 
rjbs

Attachment: signature.asc
Description: Digital signature

Reply via email to