Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the current timestamp in a Perl file?

Tags:

perl

How do I write the current timestamp in a Perl file?

I have made a file named myperl.pl which will print the current timestamp. The file is given below:

#!/usr/local/bin/perl
@timeData = localtime(time);
print "@timeData\n";

Now I am trying to redirect the output of this file into another text file. The script is below:

#!/usr/local/bin/perl
@myscript = "/usr/bin/myperl.pl";
@myfile = "/usr/bin/output_for_myperl.txt";
perl "myscript" > "myfile\n";

While running this I am getting below error:

perl sample_perl_script.pl
String found where operator expected at sample_perl_script.pl line 4, near "perl "myscript""
(Do you need to predeclare perl?)
syntax error at sample_perl_script.pl line 4, near "perl "myscript""
Execution of sample_perl_script.pl aborted due to compilation errors.

like image 828
Avisekh Das Avatar asked Sep 28 '12 17:09

Avisekh Das


1 Answers

Another tip. If you want to control the format of the timestamp, I usually throw in a subroutine like the following. This will return a scalar in the format of "20120928 08:35:12".

sub getLoggingTime {

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    my $nice_timestamp = sprintf ( "%04d%02d%02d %02d:%02d:%02d",
                                   $year+1900,$mon+1,$mday,$hour,$min,$sec);
    return $nice_timestamp;
}

Then change your code to:

my $timestamp = getLoggingTime();
like image 198
Shizeon Avatar answered Sep 24 '22 02:09

Shizeon