perlvariablescommand-linescriptingcommand-line-arguments

How can I add variables into my Perl one-liner?


I've got the following one-liner with Perl:

perl -MLingua::EN::Sentence=get_sentences -ne 'print "$_\n" for grep { /replace_me/i } @{get_sentences($_)}' "${filePath}"

How can I restructure this so that I'm able to replace the "replace_me" section with any string of text (aka, a variable) that I can pass into the script as an argument?

I understand that you cannot add variables within single quotes, but I'm not sure how to restructure this at the moment with double quotes. Any help would be appreciated.


Solution

  • A "one-liner" is a program that can take input like any other -- what is passed to the program at invocation is in @ARGV array.

    Then there are two particular issues to take into account

    Then there are three ways to bring arguments into the program.

    Fetch the arguments from @ARGV by hand

    perl -wnE'BEGIN { $input = shift };  ... '  "input string" filename(s)
    

    where ... stand for your code, just as it was, but which now can use $input.

    Another way is with -s switch which enables a rudimentary mechanism for arguments

    perl -s -wnE'...code using $input...' -- -input="input string"  filename(s)
    

    where the name given after - (I used input above) is the name of the variable in which input gets stored. The -- are there to mark the beginning of the arguments. All arguments passed to the script must be given before the filename(s).

    Finally, instead of passing arguments directly we can set a shell variable as an environment variable, which the script can then see. In bash shell we can do it in the same command-line, right before the command itself

    input="input string"  perl -wnE'...$ENV{input}...' filenames
    

    Or, set it up beforehand and export it

    export input="input string"
    perl -wnE'... $ENV{input} ...'
    

    See this post for details on all three ways.

    Once this input is used in a regex escape it using quotemeta, /...\Q$input\E.../i, unless it is meant to be a ready regex pattern. Please see the linked documentation.