Writing a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ramesh54
    New Member
    • Jul 2008
    • 37

    Writing a file

    Hello All,

    I have a small query. I have a input file z.txt and then i would edit some lines in this file and I would make the changes and save the output file as t.txt. So finally i should be having only one file t.txt in my directory and no z.txt. Is there any better option to make this code better.
    Code:
    #!/usr/bin/perl
    use warnings;
    use strict;
    
    open (IN,'+<','z.txt'); 
    open OUT,"+> t.txt"; 
    
    
    while (<IN>) {
    s/(\d+)/40 + $1/ge;
    print OUT;
    }
    close IN;
    close OUT;
    unlink ('z.txt');
    Regards,
    Ramesh
    Last edited by numberwhun; Jul 29 '08, 02:11 AM. Reason: Please use code tags
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Assuming your regexp does what you need, your code is fine. But you don't need to open IN for read/write, just read. So change this line:

    Code:
    open (IN,'+<','z.txt');
    change to:

    Code:
    open (IN,'<','z.txt');

    Comment

    • ramesh54
      New Member
      • Jul 2008
      • 37

      #3
      Thanks for your reply.

      I have another query in regexp, I have some digits for eg 20 40 60 and then I add 40 so finally my output becomes 60 80 100.

      Instead of taking the digits as a whole, I would like to add the values separately for each digits. eg: 20+10 40+30 60-20 and my output should be30 70 40.

      How do I read the digits separately and then then add the values.

      Ramesh

      Comment

      • nithinpes
        Recognized Expert Contributor
        • Dec 2007
        • 410

        #4
        Originally posted by ramesh54
        Thanks for your reply.

        I have another query in regexp, I have some digits for eg 20 40 60 and then I add 40 so finally my output becomes 60 80 100.

        Instead of taking the digits as a whole, I would like to add the values separately for each digits. eg: 20+10 40+30 60-20 and my output should be30 70 40.

        How do I read the digits separately and then then add the values.

        Ramesh
        Take out three numbers separately in regex through grouping and do the addition.

        Code:
        while (<IN>) {
        s/(\d+)(\s+)(\d+)\s+(\d+)/ ($1+10).$2. ($3+30).$2.($4-20)/ge;
        print OUT;
        }
        The space(s) in between numbers (captured in $2) are appended to the resulting output.

        Comment

        Working...