How to use shell variables in perl command call in a bash shell script?

How to use shell variables in perl command call in a bash shell script?

I have a perl command in my shell script to evaluate date -1.

How can i use $myDate in perl command call?

This is the section in my script:

myDate='10/10/2012'

Dt=$(perl -e 'use POSIX;print strftime '%m/%d/%y', localtime time-86400;")

I want use $myDate in place of %m/%d/%y.

Any help will be appreciated.

Thank you.

Answers


The same way you pass values to any other program: Pass it as an arg. (You might be tempted to generate Perl code, but that's a bad idea.)

Dt=$( perl -MPOSIX -e'print strftime $ARGV[0], localtime time-86400;' -- "$myDate" )

Note that code doesn't always return yesterday's date (since not all days have 86400 seconds). For that, you'd want

Dt=$( perl -MPOSIX -e'my @d = localtime time-86400; --$d[4]; print strftime $ARGV[0], @d;' -- "$myDate" )

or

Dt=$( perl -MDateTime -e'print DateTime->today(time_zone => "local")->subtract(days => 1)->strftime($ARGV[0]);' -- "$myDate" )

or simply

Dt=$( date --date='1 day ago' +"$myDate" )

Variables from the shell are available in Perl's %ENV hash. With bash (and some other shells) you need to take the extra step of "exporting" your shell variable so it is visible to subprocesses.

mydate=10/10/2012
export mydate
perl -e 'print "my date is $ENV{mydate}\n"'

Using " instead of ' also passes shell variables to perl in version 5.24.

mydate=22/6/2016
perl -e "print $mydate"

Why not something like: $ENV{'PATH'} = $ENV{'PATH'}.":"."/additional/path";


The same way you pass values to any other program: Pass it as an arg. (You might be tempted to generate Perl code, but that's a bad idea.)

Dt=$( perl -MPOSIX -e'my($m,$d,$y) = split qr{/}, $ARGV[0]; --$d; print strftime "%m/%d/%y", 0,0,0, $d,$m-1,$y-1900;' -- "$myDate" )

For me, I need to use $ENV{'VARIABLE'} to pass VARIABLE in shell to Perl. I do not know why simply $ENV{VARIABLE} did not work.

For example,

In Bash:

#!/bin/bash -l
VARIABLE=1
export VARIABLE
perl example.pl

In Perl:

#!/usr/bin/perl -w
print "my number is " . $ENV{'VARIABLE'}

Need Your Help

What is the use of the Hibernate @LazyCollection annotation

java performance hibernate orm lazy-loading

I have 2 entities as Parent and Child as OneToMany relation as

Retrieving UTC DATETIME field from MySQL in Java when server timezone is not UTC

java mysql date datetime jdbc

I'm trying to write code to interoperate with a third-party-developed database using Java and MySQL. This database has a field that stores a time stamp in a DATETIME field as a UTC date. The time...