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
With -n
the code under ''
is the body of a loop (over lines from the files that are processed or from STDIN
) so you want to extract your input (arguments) in a BEGIN
block, before the runtime and so before the loop starts
Arguments that are passed to the script must be removed from @ARGV
so that what remains are only filename(s), to be read line by line (under -n
, or -p
)
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 which the script will 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.