I'll walk you through this with a simpler example. Suppose you want to print the word test
.
We can do that with this one-liner:
perl -e'print "test"'
Now suppose we had the string test
stored in a variable, $FILENAME
. We could print that with
print "$FILENAME"
but we would have to set it first:
perl -e'$FILENAME="test"; print "$FILENAME"'
But what if that variable is set in bash
? You were doing that part correctly.
FILENAME=test
Let's try printing this in Perl:
perl -e'print "$FILENAME"' # prints nothing
If the variable is within the single quotes, then Perl is interpreting it. If we put it outside the single quotes, then it will be interpreted in bash and the program will be passed to the perl interpreter.
perl -e'print "'$FILENAME'"' # prints test
# open_^ ^ open__^ ^
# close________^ close___^
I like to think of it as closing the single quotes to get bash to interpret the variable, and opening them again to get to back to perl.
This has tripped me up before. You can read about it here: Why is '$_' the same as $ARGV in a Perl one-liner?
You can read about \Q...\E
here.
You might still need it, for example if you had a ?
in your variable. Quotemeta will escape special characters to match their literal character instead of using their special meaning.