Search code examples
perlstring-concatenation

How to print a string value in single line using Perl


My problem is simple one... My perl code is like below...

 $todaydate = `date +%Y-%m-%d-%H%M%S`;
 $output_file = "my_data_$todaydate".".csv";
 print "SQL query output file name : $output_file\n";

But the Output file name is printing as like below...

SQL query output file name : my_data_2017-10-03-062227
.csv

If you can observe, the .csv is coming in new line. I have also tried the below join for string conactantion. but still no luck.

$output_file = join "", "my_data_", $todaydate, ".csv";

due to this issue, while i am passing the output_file name to a sql query, its creating a file my_data_2017-10-03-062227 without .csv extension.

Any suggestion please...


Solution

  • There are several reasons why you might not want to use external programs unnecessarily.

    • The external program might not be available (or might work differently) on some systems where you want to run your program. You are therefore making your code less portable.
    • Starting a new shell and invoking an external program takes longer than just using a Perl feature to achieve the same result.
    • The value returned from an external problem will probably have a newline character at the end - and you might forget to remove it.

    Getting a date is a task that people commonly want to use an external program for. And I don't understand why, because Perl has pretty good built-in time and date handling. For example, your code can be written like this:

    use Time::Piece;
    
    $todaydate = localtime->strftime('%Y-%m-%d-%H%M%S');
    $output_file = "my_data_$todaydate.csv";
    print "SQL query output file name : $output_file\n";
    

    Time::Piece has been included with all versions of Perl since 2007. It changes the behaviour of localtime() so it returns an object. And the object has many useful methods - here we use strftime().

    If you're stuck with an older version of Perl (pre-5.10) then you can still do this easily without calling an external program.

    use POSIX 'strftime';
    
    $todaydate = strftime('%Y-%m-%d-%H%M%S', localtime);
    $output_file = "my_data_$todaydate.csv";
    print "SQL query output file name : $output_file\n";