If I had:
$foo= '12.'bar bar bar'|three';
how would I insert in the text ‘..’ after the text 12. in the variable?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Perl allows you to choose your own quote delimiters. If you find you need to use a double quote inside of an interpolating string (i.e.
'') or single quote inside of a non-interpolating string (i.e.'') you can use a quote operator to specify a different character to act as the delimiter for the string. Delimiters come in two forms: bracketed and unbracketed. Bracketed delimiters have different beginning and ending characters:[],{},(),[], and<>. All other characters*are available as unbracketed delimiters.So your example could be written as
Inserting text after ’12.’ can be done many ways (TIMTOWDI). A common solution is to use a substitution to match the text you want to replace.
the ^ means match at the start of the sting, the
()means capture this text to the variable$1, the12just matches the string'12', and the[]mean match any one of the characters inside the brackets. The brackets are being used because.has special meaning in regexes in general, but not inside a character class (the[]). Another option to the character class is to escape the special meaning of.with\, but many people find that to be uglier than the character class.Another way to insert text into a string is to assign the value to a call to
substr. This highlights one of Perl’s fairly unique features: many of its functions can act as lvalues. That is they can be treated like variables.If you did not already know where
'12.'exists in the string you could useindexto find where it starts,lengthto find out how long ’12.’ is, and then use that information withsubstr.Here is a fully functional Perl script that contains the code above.
*all characters except whitespace characters (space, tab, carriage return, line feed, vertical tab, and formfeed) that is