Perl datetime generated?

Viewed 68

I have a perl script that takes system date and write that date to a filename.

System date is assigned to TRH1 variable and then it set to a filename.

$TRH1 =`date + %Y%m%d%H%M`;
print "TRH1 => $TRH1\n";
open(TPFILE, ">./log/errTS_TPList_$TRH1.csv"); 

However, TRH1 seems to have correct value but file name has a question mark, that I do not desire.

TRH1 => 202103031940
errTS_TPList_202103031940?.csv

Can you show me how to get rid of this "?" ?

2 Answers

As you've already been shown, it's because the output from date has a newline character at the end that you need to remove with chomp().

However, there's really no need to use an external program to get the date and time. Modern versions of Perl come with Time::Piece which makes this trivial:

use Time::Piece;

# Perl style generally reserves uppercase variable names
# for constants
my $trh1 = localtime->strftime("%Y%m%d%H%M");

With an older version of Perl, you can use strftime() from POSIX:

use POSIX 'strftime';

my $trh1 = strftime("%Y%m%d%H%M", localtime);

When you execute the shell command, you need to chomp it.

Also use a modern way to write into a file, using a lexical filehandle.

Try in this way:

#!/usr/bin/perl 

use strict; use warnings;

my $TRH1 = `date +%Y%m%d%H%M`;
chomp $TRH1;

print "TRH1 => $TRH1\n";

my $filename = "log/errTS_TPList_$TRH1.csv";
open(my $TPFILE, '>:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename'";
Related