How to write current timestamp in a Perl file?

How to write current timestamp in a Perl file?

I created a file called myperl.pl that will print the current timestamp. The file is listed below:

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

Now I am trying to redirect the output of this file to 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 doing this, I get below the error:

perl sample_perl_script.pl
The string was found where the operator was expecting in the string sample_perl_script.pl 4, next to "perl" myscript ""
(Do you need to provide perl?)
syntax error in line sample_perl_script.pl 4, next to "perl" myscript ""
The execution of sample_perl_script.pl has been canceled due to compilation errors.

+7
source share
2 answers

One more tip. If you want to control the timestamp format, I usually drop the subroutine as shown below. This will return a scalar in the format "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(); 
+28
source

To write to a file, a descriptor file is required:

 #!/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 file descriptor, just print and then on the command line:

 ./script.pl > new_date_file 
+7
source

Source: https://habr.com/ru/post/1436857/


All Articles