-1

I need to find whether a value is present in a string or not using grep in if condition. I tried few code but that was incorrect

This is for windows running Perl.

$string ="This is a test string";
$val ="test";
if( grep /$val/i, $string)
print "found";
else
print "not found";

I expect the output to be found

Sahal
  • 105
  • 13
  • I need to find it using grep not with index – Sahal Sep 02 '19 at 09:41
  • 1
    Why do you specifically want to use `grep` for that purpose? – GMB Sep 02 '19 at 09:41
  • @GMB because I need to check that string with multiple values. I'll make it simple, Suppose im having an array @val=("demo","test","gone"); . So I need to check any of these values are present in the string and also need to know which value it is matched to. – Sahal Sep 02 '19 at 11:46

1 Answers1

1

grep is useful when filtering a list. String is not a list in Perl, you should just just the match or index.

if (-1 != index $string, $val) {

or

if ($string =~ /$val/i) {

Your syntax is wrong. When using if with else, curly brackets aren't optional.

if (grep /$val/i, $string) {
    print "found";
} else {
    print "not found";
}
choroba
  • 231,213
  • 25
  • 204
  • 289
  • What if I have multiple string values to match.For example, $val is an array.How to check whether anyone of the array value matches the string – Sahal Sep 02 '19 at 10:13
  • @Sahal, That's where grep is useful. – ikegami Sep 02 '19 at 11:00
  • @ikegami Can you show some demo code for that? – Sahal Sep 02 '19 at 11:43
  • @Sahal, As per [documentation](https://perldoc.perl.org/functions/grep.html), one of the usage is `grep EXPR, LIST`, and "`LIST`" means an "expression that returns zero or more scalars in list context". `@a` is such an expression. – ikegami Sep 02 '19 at 11:57