Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Thursday, June 4, 2009

Traversing directory structure in perl

Today I started learning a bit of perl and created a small program to search for a particular string in all the xml files in the current directory as well as any sub-directory and printing the count of occurence of string.

Here is the code:
#!/usr/bin/perl --  
use strict;
use warnings;
use diagnostics;
use Fatal qw/:void open close/;
#first find the .xml files in the directory recursively and store in a temp list
  $f=`find . -name "*.xml" > /tmp/fileList`; 
 open TEMPFILE, "/tmp/fileList" ;
 $subflowCount = 0; 
 # traverse throygh each xml file 
 while( ){ 
 $file = $_;  
 #if yes then look for subflow tag           
    $result=`grep -i  "" $file`;   if ( $result=~m//){
print $file."\n";
 $subflowCount = $subflowCount + 1; 
  }
 } 
 print "Total subflows are:";
 print $subflowCount; 

I have commented the code to understand what it is doing.
To run go to linux box:
do: chmod 777 
do ./

5 comments:

chorny said...

It would be easier and more readable to use File::Find module.

P.S. Add "use strict;use warnings;use diagnostics;use Fatal qw/:void open close/;" at start of your code, after #!. Later you can drop last two.

Unknown said...

Thankx and i added your suggestions.

Unknown said...

Hi @Vik good shot, but I think you are kidding yourself if you think this is perl;-)

Suggest you try to do the same thing, but without using any backticks or system calls. Like many tasks, this is possible in pure Perl - no O/S calls at all. (Which btw makes it a great language for cross-platform database scripts since perl is installed by default with Oracle -- as long as you steer clear of the O/S calls!)

I spend more time forgetting Perl than learning it, so I always have my trusty O'Reilly 'animal books' near to hand. The Perl Cookbook is always the first I reach for, and it has all the recipes you need for this. If you don't already have a copy, I couldn't recommend it more highly.

Anonymous said...

I inclination not agree on it. I regard as nice post. Especially the appellation attracted me to study the whole story.

Anonymous said...

Good brief and this fill someone in on helped me alot in my college assignement. Thank you on your information.