Question:

Perl command?

by  |  earlier

0 LIKES UnLike

$dir = "/folder1/folder2/folder3"; >> Problem 1

if(opendir(DIR,$dir)) {

foreach my $filename (readdir DIR) {

if($filename =~ /*.xml$/i) { >> Problem 2

if(open(Open_Input,"$dir/$filename")) {

#do whatever you want

I'm new in perl and have 2 problems with the above code. What i want is to open specific folders and searh for all the xml files. However in Problem1 the folder names changes for example folder2 may sometimes be folder8 or folder10 so i can't specify a fixed folder. Also I get an error in Problem 2 for searhing all the xml files in a folder please help???

 Tags:

   Report

2 ANSWERS


  1. If you want to write the program yourself, that first bit would be best to write as a recursive function, as suggested.  Something like:

    my(@xml_files) = find_xml("/base_folder");

    sub find_xml {

      my($dir) = @_;

      return undef unless(-d $dir); #skip things that aren't valid dirs

      return undef unless(opendir(XML_DIR,$dir)); #skip things you can't open

      my(@xml_files) = ();

      foreach my $file (readdir(XML_DIR)) {

        next if($file =~ /^\.\.?$/); #don't get stuck in a loop or go backwards up the dir tree

        if(-d "$dir/$file") {

          push @xml_files,find_xml("$dir/$file");

        } elsif(-f "$dir/$file" && $file =~ /\.xml$/i) {

          push @xml_files, "$dir/$file";

        }

      }

      return @xml_files;

    }

    In problem 2, your regex is incorrect-- the asterisk must follow a character.  In this case, you want it to be:

    /.*.xml$/i

    But even that's not completely correct, because the filename "ilove.myxml" would match, when you probably don't want it to.  Instead, because the "." is a single character wildcard, and you probably mean the literal character, you really want:

    /.*\.xml$/i

    But even that is kind of extraneous, because the ".*" will match anything or nothing.  So you might as well just say:

    /\.xml$/i

    (Note that's the regex I used in my example)

    DaveE


  2. You need to use RECURSION to look into folders and subfolders.  Hint: write a function that takes a path name, tests whether it's a folder or a file, and does the right thing accordingly.

    You could also use the File::Find module which does all this for you.  
You're reading: Perl command?

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions