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

How do I find all occurrences of string that ends with the characters $$? The value of $rc in the code below is null.

my $matchmember='PARJT$$'; my $target='PARJT## PARJT$$ PARJT##'; my $rc; $rc=grep /$matchmember/,$target;

Replies are listed 'Best First'.
Re: Need to grep for a string that ends with $$
by toolic (Bishop) on Mar 06, 2012 at 15:48 UTC
    Another way is to use quotemeta:
    use warnings; use strict; my $matchmember = quotemeta 'PARJT$$'; my $target = 'PARJT## PARJT$$ PARJT##'; my $rc = grep /$matchmember/, $target; print "$rc\n"; __END__ 1
Re: Need to grep for a string that ends with $$
by moritz (Cardinal) on Mar 06, 2012 at 15:48 UTC

      The OP said that $matchmember ends with $$, not that $target must end with $matchmember.

      That means the "$" shouldn't be there.

      if ($target =~ /\Q$matchmember\E/) { print "Match!\n"; }

      And since the \E is trailing, it can be omitted.

      if ($target =~ /\Q$matchmember/) { print "Match!\n"; }

      Finally, he asked to find all occurrences, so it would be more like:

      my @matches = $target =~ /(\Q$matchmember\E)/g;

      or

      while ($target =~ /(\Q$matchmember\E)/g) { print "Found $1 at $-[1]\n"; }
Re: Need to grep for a string that ends with $$
by JavaFan (Canon) on Mar 06, 2012 at 15:48 UTC
    Three problems here. First, $ a special meaning, so '$$' means something else than two $'s in a row. But second, $target does not actually end with $$, so you will not get a match. Third problem, you're executing grep in scalar context, so all you get is the number of matches, not the matches. Perhaps you want (untested):
    my @matches = grep /\$\$$/, split ' ', 'PARJT## PARJT$$ PARJT##';
Re: Need to grep for a string that ends with $$
by wallisds (Beadle) on Mar 06, 2012 at 15:47 UTC

    Consider using regular expressions to do your matching:

    my $string = 'PARJT$$'; if ($string=~m/\$\$$/) { print "match"; }

    The backslashes are used to literally match the $ which otherwise is interpreted as the special character which represents the end of the string. We use a bare $ later to show we are only looking for matches at the end of the string.

A reply falls below the community's threshold of quality. You may see it by logging in.