3

A newbie to Perl and regexes without saying, I am trying to use elements in an array in a perl regex. Here is the snippet

my $temp  = $line =~ s/somestring[^\n]*$_// for @myarray;

If I hard code the string instead of $_ it works fine. Also $_ prints the string fine in isolation. So what am I doing wrong? Even the expanded version of using a for loop doesn't yield a match.

P.S Just to clarify the array has just one element and I know it matches the line.

5
  • I'm not a Perl dev, but in REGEX $ has special meaning - it anchors to the end of the string, so it may need escaping. Commented Jul 13, 2012 at 17:33
  • @utkanos: Not necessary. Scalar variable interpolation works just fine inside of Perl regular expressions. perldoc perlop under the section "Quote and Quote Like Operators". Commented Jul 13, 2012 at 17:45
  • This is why I posted as a comment, not an answer. I was just saying that, in general REGEX grammar, the $ has special meaning. I'm not a Perl dev, so I didn't commit - I was just floating the idea. Commented Jul 13, 2012 at 17:50
  • A little more code might help, like actual values that illustrate the problem. I'm not sure what you're trying to accomplish or how it is failing. Commented Jul 13, 2012 at 18:10
  • Thank you @RickF. It did turn out to be a rather trivial oversight/misconception on my part and my question was answered. Commented Jul 13, 2012 at 18:21

1 Answer 1

4

It should work adding parentheses, although I hope that the content of the array hasn't special characters, because you will need to use quotemeta function to escape them.

my $temp;
($temp  = $line) =~ s/somestring[^\n]*$_// for @myarray;
Sign up to request clarification or add additional context in comments.

2 Comments

The "special characters" issue is a good point. s/somestring[^\n]*\Q$_\E// is the more robust solution, unless the OP really wants the contents of $_ to be treated as a pattern.
Thank you ! It helped. Robust solutions are always desirable. Helps me to start learning perl better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.