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

Scanning a directory for XML files and reading them

P: 79
Hello,

I would like to scan a certain directory for XML files. Then I want to take in every XML file, read it, and stores the contents as a string in an array. For example, if the directory has file1.xml, file2.xml, and file3.xml, they would all be scanned and read. Then, all the contents of file1.xml would be stored in an array as the first element:

@array[0] would contain the stuff in file1.xml
@array[1] would contain the stuff in file2.xml
etc.

This is what I have:

Expand|Select|Wrap|Line Numbers
  1. sub getComponents
  2. {
  3.     my            $dir                     = shift;
  4.     my             @Components        = ();
  5.     my            @xmlFiles                = ();
  6.  
  7.     if ( -d $dir )
  8.     {
  9.         open ( COMPONENTS, $dir );
  10.         @xmlFiles = grep ( /^(.+)\.xml$/, grep ( !/^.{1,2}$/, readdir( COMPONENTS ) ) );
  11.         closedir ( COMPONENTS );
  12.  
  13.         $dir = addSlash( $dir );
  14.  
  15.         foreach ( @xmlFiles )
  16.         {
  17.             my @fileInfo = readTextFile ( $dir . $_ );
  18.             push( @Components, \@fileInfo );
  19.         }
  20.     }
  21.  
  22.     return @Components;
  23. }
readTextFile is another sub that has been tested. No problems there. addSlash adds a slash at the end of the directory so that the files can be opened. This is also tried and tested.

The problem is this code simply doesn't work. I don't know where to start looking.

Thanks
Oct 1 '07 #1
Share this Question
Share on Google+
1 Reply


eWish
Expert 100+
P: 971
The open function opens a file not a directory. Use opendir to open the directory. Also, add some error checking to make sure the directory is actually being opened and read.

Excerpt form perldoc:
Expand|Select|Wrap|Line Numbers
  1.     opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
  2.     @dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
  3.     closedir DIR;
Oct 2 '07 #2

Post your reply

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