LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Perl: how to access multiple directory with variables (http://www.linuxquestions.org/questions/linux-newbie-8/perl-how-to-access-multiple-directory-with-variables-4175452832/)

kwoweiho 03-05-2013 02:17 PM

Perl: how to access multiple directory with variables
 
I want to access multiple directories with the following structure and concatenate all the files from each director into one file:
/a/b/c/1
/a/b/c/2
....
/a/b/c/22

Here's my code in perl:

@chr=(1 .. 22);
$n=0;
while ($chr[$n]) {
$path = "/a/b/c/$chr[$n]";
opendir(DIR, $path) or die “Cannot open $path : $!”;
system (cat * >/a/b/c/$chr[$n].txt);
closedir(DIR);
$n++;
}

there's an error in the opendir line. and maybe more, can somebody help me out please?
Thanks!
David

chrism01 03-05-2013 05:43 PM

Best practice is to start code with warnings & strict turned on
Code:

#!/usr/bin/perl -w
use strict;

It would also help if you showed the error msgs you're getting.
Incidentally, you should add error handling to closedir as well.

I'd guess at least one problem is you are opening a DIR to read, but you're not changing to that dir ( chdir() ), so the cat is working in the the wrong dir.
http://perldoc.perl.org/

smallpond 03-05-2013 07:35 PM

First time with Perl?

I think you are confusing opendir with chdir:

Code:

use warnings;
use strict;

for my $dir (1 .. 22) {
  chdir "/a/b/c/$dir";
  system("cat * >/a/b/c/$dir.txt");
}


kwoweiho 03-06-2013 10:03 AM

Thanks guys, it works perfectly!


All times are GMT -5. The time now is 06:42 PM.