How to write the current timestamp in a Perl file?

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.

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();

You need a file-handle to write to a file:

#!/usr/local/bin/perl

use strict;
use warnings;

my $timestamp = localtime(time);

open my $fh, '>', '/tmp/file'
   or die "Can't create /tmp/file: $!\n";

print $fh $timestamp;

close $fh;

Some documentation: open, Leaning Perl

Another solution is a script without a filehandle, just a print, then on the command line:

./script.pl > new_date_file

Need Your Help

ifconfig command not found

linux centos command ifconfig

I've just installed CentOS7 as a virtual machine on my mac (osx10.9.3 + virtualbox)

How to make an UIPickerView with a Done button?

ios swift uipickerview

I am having difficulties to make an UIPickerView with a done button to appear when the users taps a UITextField. This is my code so far. Everything builds fine, but when I tap the text field, the