I have defined a variable in bash

$ MYDATESTAMP="2009-06-25 21:57:18"

I would like to pass this to perl to perform a simple date conversion.

If I enter the date manually it works.

$ perl -MDate::Parse -le'print str2time("2009-06-25 21:57:18");'
$ 1245992238

My attempts to pass the variable MYDATESTAMP into this command it returns nothing.

$ perl -MDate::Parse -le'print str2time("$MYDATESTAMP");'

How can this be done?

Ok, I figured out a way to do this. It's not elegant, but it managed to get the job done.

What I did was echo the $MYDATESTAMP variable from bash into a file named mydatestamp.txt and had a tiny perl script which I named "foo.pl" read that file and then perform the date format conversion.

bash

#echo the datestamp to a text file. 
echo $MYDATESTAMP > mydatestamp.txt
# Set a new variable by having perl read the text file and convert the time format
MYDATESTAMP2=$(/usr/bin/perl foo.pl)

foo.pl (perl)

#!/usr/bin/perl
use Date::Parse 'str2time';
open (MYDATESTAMP, "mydatestamp.txt");
 while ($record = <MYDATESTAMP>) {
      my $date = $record;
      my $epoch = str2time($date);
	  #print "Epoch: $epoch\n";
      #print $record;
      print "$epoch"
}
close(MYDATESTAMP);

export the variable and use $ENV:

sk@sk:~$ export MYDATESTAMP="2009-06-25 21:57:18"
sk@sk:~$ perl -MDate::Parse -le'print str2time($ENV{"MYDATESTAMP"});'
1245981438

Thanks! That's much better than my caveman solution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.