Search code examples
perldouble-quotesquoting

How to surround a string in double quotes


I have a file with the following

firsttext=cat secondtext=dog thirdtext=mouse

and I want it to return this string:

"firsttext=cat" "secondtext=dog" "thirdtext=mouse"

I yave tried this one-liner but it gives me an error.

cat oneline | perl -ne 'print \"$_ \" '

Can't find string terminator '"' anywhere before EOF at -e line 1.

I don't understand the error.Why can't it just add the quotation marks?



Also, if I have a variable in this string, I want it to be interpolated like:

firsttext=${animal} secondtext=${othervar} thirdtext=mouse

Which should output

"firsttext=cat" "secondtext=dog" "thirdtext=mouse"

Solution

  • What you want is this:

    cat oneline | perl -ne 'print join " ", map { qq["$_"] } split'
    

    The -ne option only splits on lines, it won't split on arbitrary whitespace without other options set.