Manipulating a txt file with Perl

redfox's Avatar, Join Date: Apr 2009
Newbie Member
hello everyone, im new to perl and hoping for someone to help me...i have a file of the form :- file.txt, the contents are as follows:-
2009-03-13 00:03:10 7599171 2639128 6480404 2639 0023
2009-03-13 00:03:14 48020 4478014 2341060 4478 0182
2009-03-13 00:03:17 44476 4916057 2620157 4917 0000

what im hoping to do is to write a perl script that will remove the whitespaces and replace with a , delimiter so that it looks like this:-


The perl script should be able to process this file in a directory say /jumbo/in and once the file is processed it should be moved to /jumbo/out

Attached is my perl script that i have come up with needless to say it doesnt work:-

use strict;                                                            
use warnings;                                                          
use File::Copy;                                                        
my @files=</jumbo/in/'>;                                                                                                                                                       
while ( <*.txt> ){                                                     
     open (FH,$_) or die "failed to read $_: $!";                      
     while(my $line = <FH>){                                           
        open(OUT,">>" ,"temp") or die "failed open temp for write' $!";                                                          
        @bits = split(/\s+/,$line);                                    
        for ($i=0;$i < $#bits;$i++)                                    
        if ($i < 5 ) { print "$bits[$i],"; }                           
        else { print "$bits[$i] "; }                                   
     print OUT $line;                                                  
     move("temp","/jumbo/out/".$_) or die "cannot rename temp:$!\n";   
     unlink $_ or die "Cannot remove $_:$!\n";                         
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Moved to PERL forum
murugaperumal's Avatar, Join Date: Feb 2010
Go4Expert Member
Dear Friend,

You can use the following coding. But it is working for only file. because I have used only one file.

The file contents are available in the following file /jumbo/in/file.
The following program also available in the same directory.

Then I have created another file in the directory /jumbo/in/. That file is used to write the content after the replace the space as ",".

use strict;
use warnings;
open(FH,'<file') or die "$! can't open";
open (FH1,'>file1') or die "$! can't open";
my $var;
    $var=~s/ /,/g;
    print FH1 $var;
system('mv file1/jumbo/out/');

But the above code only work for only one file. If you want to perform the operation multiple files or single file. But your code will show me as multiple files.