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

How to grep on a scalar value,the following grep is yieldin a value of zero?

$folder_present = grep (/^\Q$folder\E$/i, $mk); print $folder_present #prints zero

Replies are listed 'Best First'.
Re: Grep failing
by davido (Cardinal) on Mar 21, 2011 at 07:28 UTC

    grep is usually used to sift through an array or list. You're passing it a scalar variable, not a list. That's one problem. What do you think $mk contains?

    grep in scalar context will return a count of how many matches it found in the list passed to it. So it would seem that whatever it is that $mk contains, it does NOT contain anything that matches with the expression, "/^\Q$folder\E$/". Since it doesn't match (not even once), the number of hits is zero, and that's what gets passed back from grep to $folder_present. grep isn't failing, as your post's title suggests. It's doing what it's designed to do.

    What are you trying to accomplish? I don't mean what do you want this little snippet to do. I mean what is the bigger picture here? What is your goal?


    Dave

Re: Grep failing
by wind (Priest) on Mar 21, 2011 at 16:25 UTC

    Based off your very limited description, I'm surmising that $mk contains a return delimited list of folders and you're trying to determine if $folder is present.

    As davido already pointed out, grep is not what you need for this because that is meant only for array operations. If you're just working on a scalar, you can do the test directly. Secondly, based off your regex, I suspect your problem is you're not using the 'm' modifier which would make it so ^ and $ matched the beginning and end of any line within the text, not just the start and end of the string.

    Here's an example that does match like you want

    my $mk = <<'END_LIST'; /foo/bar /foo/baz /eep/foo/bar /epp/foo/baz /biz /baz/foo/bar END_LIST my $folder = '/foo/baz'; my $folder_present = $mk =~ /^\Q$folder\E$/im; print "$folder_present"; # Prints 1

    - Miller

      Does anyone have any idea why the below if condition is failing for the given input?

      $folder:FileMuxInternaldefs $mk:./AACBaseFileLib/common.mk: $(PROJECT_ROOT)/../FilemuxInternalDef +s/inc \ if ($folder =~ /$mk/i) #this match failing for the give +n input { print "\nIN\n"; if ($folder !~ /$mk/m) { print "CASE-SENSITIVE:$mk\n"; } }

        Probably for the same reason when you asked here, FOR LOOP not entered.

        Your code does not actually run because of this nonsense

        $folder:FileMuxInternaldefs $mk:./AACBaseFileLib/common.mk: $(PROJECT_ROOT)/../FilemuxInternalDef +s/inc \
Re: Grep failing
by Anonymous Monk on Mar 21, 2011 at 16:40 UTC