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

need help for matche and insert

P: 1
I am trying to match two patterns in a file and insert a line. If the patterns matche then insert a line after the second matching pattern line.

for example,
I have the following content in a file:

//This is my source file

Expand|Select|Wrap|Line Numbers
  1. pin(name1) { 
  2. clock; 
  3. capacitance; 
  4. direction: input; 
  5. //this is where i want to insert a line 
  6. min_pulse; 
  7. pin(name2) { 
  8. clock; 
  9. capacitance; 
  10. direction: input; 
  11. //this is where i want to insert a line 
  12. max_pulse; 
  13.  
I have to match for two patterns "pin" and "direction:input" and then insert a line after the second pattern match.
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -w 
  2. open(FILE, " <sdv.lib") ¦ ¦die "can not open this file\n"; 
  3. open(OUTFILE,">out_sdv.lib") ¦ ¦die "can not create outfie"; 
  4. $i=0; 
  5. $search="pin(.+){"; 
  6. $second="direction(.+)input(.+)"; 
  7. $add="max_tran: 500;\n"; 
  8. @source= <FILE>; 
  9. while(@source){ 
  10. if($source[$i]=~/$search/){ 
  11. $j=$i; 
  12. for($i;$i <=$j+3;$i++){ 
  13. if($source[$i]=~/$second/){ 
  14. print OUTFILE $source[$i]." ".$add; 
  15. else{ 
  16. print OUTFILE $source[$i]; 
  17.  
  18. else{ 
  19. print OUTFILE $_; 
  20. $i++; 
  21. close(FILE); 
  22. close(OUTFILE); 
  23.  
The above code did not work. Could you tell me what's wrong this program?
Jul 20 '08 #1
Share this Question
Share on Google+
2 Replies


KevinADC
Expert 2.5K+
P: 4,059
Your code, while it could be written better, appears as though it should work or is close to working. I think if you put a little more effort into debugging you will get it working. If not, let me know and I will try and help.
Jul 20 '08 #2

nithinpes
Expert 100+
P: 410
The while(@source) {} loop will result in an infinite loop unless you are removing elements of @source inside the while loop using pop() or shift().
In your case, since you have used variable index throughout the script, you can replace while(@source) with:
Expand|Select|Wrap|Line Numbers
  1. for($i=0; $i<=$#source; $i++) ## remove additional $i++; at the end of your loop
  2.  
Other than this, the rest of the script seems fine and should work.
Jul 21 '08 #3

Post your reply

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