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

Hi I am trying to insert a variable in 2nd line of a file. But it never takes variable value rather keeps taking it as text.

root@vm-test-001:~/mongosearch# part=( "${arr[@]:i:batchsize}" ) root@vm-test-001:~/mongosearch# echo $part "C:00000092666270:53882159774" root@vm-test-001:~/mongosearch# perl -ni -e 'print; print "permissib +leCars = [ \${part[*]} ]\n" if $. == 2' query/containerId_count.js

This keeps inserting $part as text like permissibleCars = [ ${part*} ] and not as variable like permissibleCars = "C:00000092666270:53882159774" How can this get fixed ?

Replies are listed 'Best First'.
Re: Inserting Variable Through Perl
by hippo (Archbishop) on Aug 17, 2017 at 07:55 UTC

    This is a problem with the shell, not with perl. If you use single quotes in the shell it won't interpolate. eg.

    $ part="C:00000092666270:53882159774" $ echo $part C:00000092666270:53882159774 $ echo '$part' $part

    Use double-quotes to interpolate or (easier) just unquote the variable when you want to use it. Better still, put it in the environment so perl can access it through %ENV.

Re: Inserting Variable Through Perl
by haukex (Archbishop) on Aug 17, 2017 at 07:59 UTC

    You can use %ENV to access environment variables, or as a trick you can use the -s switch:

    $ cat test.txt one two three $ part="C:00000092666270:53882159774" $ echo $part C:00000092666270:53882159774 $ perl -pse 'print qq{foo = [ "$bar" ]\n} if $. == 3' -- -bar="$part" +test.txt one two foo = [ "C:00000092666270:53882159774" ] three $ export part $ perl -pe 'print qq{foo = [ "$ENV{part}" ]\n} if $. == 3' test.txt one two foo = [ "C:00000092666270:53882159774" ] three

    I removed the -i for demonstration purposes, you can just add it back in, also I used -p instead of -n to save a bit of typing, but neither of those changes are necessary for the ideas I'm showing to work.

    Although personally, I usually prefer to just write the whole thing in Perl instead of intermixing Perl and shell scripting.