A. K.
A. K.

Reputation: 38156

Making nested/recursive directories using Perl

I have written a C++ program that reads in a file and outputs the file with the same name with slight modifications. Now I need to browse recursively into the directory (of any package) and then create files in a separate directory having same directory structure.

I can browse into the directory by using

@file_list = `find <package directory> -name '*.cpp'`;

And I'm trying to execute my program like this:

foreach (@file_list) {
    # This gives error as sh: other_dir/./lev1/lev2/filename.cpp: not found
    ./myexe $_ other_dir/$_;
}

Previously I had written a shell script which worked good with packages having files in a single directory. The script is as follows:

  1 #!/bin/bash
  2 #echo off
  3 rm -rf demac_dir
  4 mkdir demac_dir
  5 for i in `ls *.h *.cpp`
  6 do
  7 echo processing file ${i} ...
  8 ./main ${i} demac_dir/${i}
  9 done

Now I'm trying to so the same thing with a package (i.e. wxWidgets) which has .cpp and .h files in nested subdirectories. So I wrote the following Perl script (after ysth's suggestion).

  1 #!/usr/bin/perl -l
  2 use File::Path 'make_path';
  3 use File::Basename 'dirname';
  4
  5 `rm -rf demac_dir`;
  6 `mkdir demac_dir`;
  7 @l1 =  `find . -name '*.h'`;
  8 @l2 =  `find . -name '*.cpp'`;
  9 @l3 =  `find . -name '*.cc'`;
 10 push(@l , @l1, @l2, @l3);
 11 foreach (@l) {
 12   print "processing file $_ ...";
 13   make_path( dirname( "demac_dir/$_" ));
 14   ## `touch touch demac_dir/$_`;
 15   `sudo ./main $_ demac_dir/$_`;
 16 }
 17

Upvotes: 1

Views: 1664

Answers (2)

Yordan Georgiev
Yordan Georgiev

Reputation: 5430

Check the FileHandler.pm and TemplateGenerator.pm from morphus

Upvotes: 1

ysth
ysth

Reputation: 98398

Err, you are missing a system() or something there that I presume is in your real code.

To make the directories you need, try:

use File::Path 'make_path';
use File::Basename 'dirname';

foreach (@file_list) {
    make_path( dirname( "other_dir/$_" ) );
    ...
}

Update: seeing your code, it looks like you are leaving newlines on the end of the filenames, which are probably causing you trouble (though I don't see why your ./main processor would produce the error you say it does...).

Add a chomp(@l); before your foreach loop.

Upvotes: 1

Related Questions