in reply to Extracting money from a double quoted string

The problem in the piece of code you showed is due to the way you are populating the string (Perl sees the $ sign as the beginning of the name of a variable. In the example you've shown, you could use single quotes to get rid of the problem, or you could escape the $ sign to give it its literal value and thereby preventing interpolation.

But if you have a HUGE string, then it is presumably coming from a file or some other external source (STDIN, another program, socket, etc.). In that case, I do not see how you could encounter the problem you are describing.

Please give some additional information on how you get this huge string populated.

  • Comment on Re: Extracting money from a double quoted string

Replies are listed 'Best First'.
Re^2: Extracting money from a double quoted string
by sherab (Scribe) on Dec 06, 2014 at 18:50 UTC
    Thanks Laurent. That's it exactly, I am populating the string from file slurp. So far your answer is the only one I have seen that reasonably even tries to answer my question and help me solve my problem. I am aware that variables try to interpolate in a "string" versus 'string' (happy nitpickers?).

      The code you posted already works for me, with the simple change of double to single quotes:

      #!/usr/local/bin/perl $string='Price is $9.99 on our website'; ($money) = $string =~ m/is\s\$([0-9]{1,2}\.[0-9]{2})\son/g; print $money; __END__ 9.99

      You can help us help you better by posting a short, self-contained program that we can use to reproduce your problem.

        You'll note that I pointed out in my original question that it works with ' '. Thanks
      If you are slurping your data from a file, then you will not have any problem with variable interpolation, and the $ sign will not give you any trouble. It is only if you are creating the string yourself in your code with double quotes that this "problem" arises. If you read data from a file, no variable interpolation occurs, so that it is as if you had used single quotes.

      And this is also basically what Corion said in the first place, but maybe you did not understand fully how it applied to your question.