Below code snippet when executed from within a perl script, gives only $datetime."12/31/9999,AUTO,.$datetime as ouput.

my $datetime=`date "+%D %r"`;
        open(FIN,"<$file_in") or die $!."\n";
        open(FOUT,">$file_out") or die $!."\n";
        my @lines=<FIN>;
        close(FIN);
        foreach(@lines){
                $msg=$_;
                chomp($msg);
                $msg=$msg.",".$datetime.",12/31/9999,AUTO,".$datetime;
                print FOUT $msg."\n";
        }
        close(FOUT);

If i remove the chomp though, it gives me the line of <FIN>, followed by newline, followd by the appended items. Help please?

The file <FIN> was ftp'd in binary mode. Could this be an issue?

It seems that when you do @lines=<FIN>, each new line in the content will become an empty line inside the array. You could simply add print "--$msg--\n"; between line 7 and 8 to see what you got from reading each line.

#For example, a file content is as follows:
Min:18 | Max:903347710
Start: 1358360970686

#The print out of each line content is as follows:
--Min:18 | Max:903347710
--
--Start: 1358360970686
--

Hi voidyman,

There is a better way of writing the perl code you showned.

  1. Use a 3 agrument open function like

open my $fh,'<',$filename or die "can't open file: $!";

  1. Don't use a bareword for filehandles like FILE_OUT etc Instead use a lexical filehandles as showned in (1.) above

  2. Why use a backtick and a system date when you can use a perl function to generate your date and make your script more portal for other systems.

Below is the modified version of your script which takes care of the return charater.

use warnings;
use strict;

use POSIX qw(strftime);

my $datetime = strftime "%c %p", localtime();
my $msg = "";

my ($file_in, $file_out) = @ARGV;  ## specify your files from CLI

open my $fh_out, '>', $file_out or die "can't open file: $!";
open my $fh_in,  '<', $file_in  or die "can't open file: $!";
while (<$fh_in>) {
    chomp;
    $msg .= $_ . "," . $datetime . ",12/31/9999,AUTO," . $datetime;
    print $fh_out $msg, $/;
}
close $fh_in  or die "can't close file: $!";
close $fh_out or die "can't close file: $!";

Please note that I don't know what your input file is.... But from your command Line interface you can specify them...

thanks!.
The issue was that the file was awindows file and the ^M characters in the end were messing around with my code.
I did not know the three variable way of file handling. TIL :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.