By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,661 Members | 1,330 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,661 IT Pros & Developers. It's quick & easy.

Writing a file

P: 37
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.
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4.  
  5. open (IN,'+<','z.txt'); 
  6. open OUT,"+> t.txt"; 
  7.  
  8.  
  9. while (<IN>) {
  10. s/(\d+)/40 + $1/ge;
  11. print OUT;
  12. }
  13. close IN;
  14. close OUT;
  15. unlink ('z.txt');
  16.  
Regards,
Ramesh
Jul 28 '08 #1
Share this Question
Share on Google+
3 Replies


KevinADC
Expert 2.5K+
P: 4,059
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:

Expand|Select|Wrap|Line Numbers
  1. open (IN,'+<','z.txt'); 
change to:

Expand|Select|Wrap|Line Numbers
  1. open (IN,'<','z.txt'); 
Jul 28 '08 #2

P: 37
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
Jul 29 '08 #3

nithinpes
Expert 100+
P: 410
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.

Expand|Select|Wrap|Line Numbers
  1. while (<IN>) {
  2. s/(\d+)(\s+)(\d+)\s+(\d+)/ ($1+10).$2. ($3+30).$2.($4-20)/ge;
  3. print OUT;
  4. }
  5.  
The space(s) in between numbers (captured in $2) are appended to the resulting output.
Jul 29 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.