467,202 Members | 1,016 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,202 developers. It's quick & easy.

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.
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
  • viewed: 969
Share:
3 Replies
KevinADC
Expert 2GB
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
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 256MB
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.

Similar topics

48 posts views Thread by Joseph | last post: by
6 posts views Thread by Sebastian Kemi | last post: by
3 posts views Thread by ishekar | last post: by
2 posts views Thread by melanieab | last post: by
reply views Thread by Yunus's Group | last post: by
16 posts views Thread by Claudio Grondi | last post: by
6 posts views Thread by arne.muller@gmail.com | last post: by
3 posts views Thread by Barry Flynn | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.