awk offers a convenient way to pass named variables to a script using the -v flag (e.g., awk -v var="value" ...), a facility that is quite useful when composing ad hoc scripts. Can the same be done with Perl or does one need to resort to argv, getopts, %ENV, interpolation by the shell through appropriate quoting, etc.? The -s option can give the desired effect but is limited to boolean values.
2 Answers
Thanks to meuh for pointing out the use of the -s option for the purpose of passing arbitrary data as opposed to simply toggling switches; after further investigation, the correct syntax for one-liner use of the -s option turned out to be the following:
$ perl -se 'print "xyz=$xyz\n"' -- -xyz="abc"
xyz=abc
The following demonstrates reading awk-like variable assignments from the command-line as well as accepting in-line perl code in a shell script:
# cat test.sh
perl - FS=':' GRP='50' <<'EOF'
eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
print "$FS\n";
print "$GRP\n";
EOF
This is the proof:
# sh test.sh
:
50
And here is an alternative form of the OP's answer that accepts inline, multi-line perl code:
# cat test.sh
perl -s -- - -xyz="abc" <<'EOF'
print "xyz=$xyz\n";
EOF
And the proof:
# sh xyz.sh
xyz=abc
This format looks very similar to awk written in a shell script, and makes it easy to replace translated non-trivial awk code with a2p generated perl code without having to resort to putting the code in a separate file.
-sis not limited to boolean. Eg-s -xyz=abcandprint $xyz\n". From the man page,perldoc perlrun.#!/usr/bin/perl -sin it for it to work!