[sf-perl] Embedded Perl in a Korn shell program

David Thompson dat1965 at yahoo.com
Fri May 11 16:53:06 PDT 2007

--- "Loo, Peter # PHX" <Peter.Loo at source.wolterskluwer.com> wrote:
>   export YYYY=`echo $YYYYMMDD | cut -c1-4`
>   export MM=`echo $YYYYMMDD | cut -c5-6`
>   export DD=`echo $YYYYMMDD | cut -c7-8`
>   MMDD=`perl -MTime::Local -MPOSIX -le \
>           '$secs = timelocal(0,0,0,$ENV{DD},$ENV{MM}-1,$ENV{YYYY}) +

Let me take a stab at a worthy explanation that addresses the
original question.

Without the export above, you would have had to adjust your
quoting to insert the values of the shell variables directly
into the perl program, like this,

    '$secs = timelocal(0,0,0,'$DD','$MM'-1,'$YYYY') + 86400; \
                              ^^^   ^^^     ^^^^^

The ^^^ are used to point out the shell variables.

Larger explanation:
You close the quote for the perl code (so that you're back to shell)
and so $DD is the shell variable, reqoute to add a comma for perl,
then unquote to insert $MM shell variable, requote to tell perl to
subtract one, unquote to insert shell's $YYYY, then requote for perl.
But that is pedantic.  If you really know what you're doing, you
could have shortened that to this,

    '$secs = timelocal(0,0,0,'$DD,$MM-1,$YYYY') + 86400; \

because ksh will correctly expand this portion,


as you would expect.  You have to know shell parsing syntax pretty
well to know why this produces correct results.

Turning quotes on and off like this is a pain, but is quite
common and historical technique for inserting values of shell
variables directly into inline awk programs inside shell scripts.

But since perl has its $ENV, it's much cleaner to export the shell
variables (exporting a shell variable 'promotes' it to an environment
variable, thus available via perl's $ENV hash) and thus you can stay
completely inside perl to fetch the value of the exported shell
variable, happily avoiding the traditional thorny quoting issues of



____________________________________________________________________________________Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games.

More information about the SanFrancisco-pm mailing list