Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Mar 2011
    Posts
    31
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Cannot print modified string to a file

    Hi,
    I made this script, it finds and modifies a string in a file. I’d like to print the modified string back to the file or to write a new file with the modified string.
    Could you help me with this problem?
    Thanks, vl123456

    Code:
    open(IN,"<","$infile2") or die $!;
    open (OUT,">>","$outfile2") or die $!;
    while (<IN>) 
         {
           if ($_ =~/Time:/gi) 
         {
             @array = split (/\s+/, $_) ;
         } 
             foreach (@array) 
         {  
              @tmp = @array[5];
              @array[1] = @tmp ;            	       	              
         } 
         {
          print "@array\n" ; 
         } 
          print OUT ;
         }
         
         sleep 4 ;
    close IN;
    close OUT ;
    Last edited by FishMonger; 04-09-2011 at 09:18 PM. Reason: vl123456 - Please use the code tags

  • #2
    New Coder
    Join Date
    Oct 2006
    Posts
    68
    Thanks
    0
    Thanked 28 Times in 28 Posts
    You aren't print anything out to the file. The empty print statement only works when printing to STDOUT. Gotta use one of the following:

    Code:
    print OUT $_;
    
    #or
    
    print OUT "@array\n";

  • Users who have thanked miller for this post:

    vl123456 (04-22-2011)

  • #3
    New Coder
    Join Date
    Mar 2011
    Posts
    31
    Thanks
    25
    Thanked 0 Times in 0 Posts
    Thanks for your help (and from another form) guys.
    I finely got it.
    Here is what I was missing:


    if ($_ =~/Time:/gi)
    {
    @array = split (/\s+/, $_) ;
    print "Old: @array\n";

    $tmp = $array[5];
    $array[1] = $tmp ;
    print OUT "@array\n" ;
    }
    else{
    print OUT "$_";
    }
    }

  • #4
    New Coder
    Join Date
    Oct 2006
    Posts
    68
    Thanks
    0
    Thanked 28 Times in 28 Posts
    Your code could be simplified to the following:

    Code:
    if (/Time:/i) {
    	my @array = split /\s+/;
    	print "Old: @array\n";
    
    	$array[1] = $array[5];
    
    	print OUT "@array\n" ; 
    } else {
    	print OUT $_;
    }

  • Users who have thanked miller for this post:

    vl123456 (04-22-2011)

  • #5
    New Coder
    Join Date
    Mar 2011
    Posts
    31
    Thanks
    25
    Thanked 0 Times in 0 Posts
    Miller, you are something man!
    Thank you! Yes, it is better.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •