-   Linux - Newbie (
-   -   Perl: how to access multiple directory with variables (

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:

Here's my code in perl:

@chr=(1 .. 22);
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);

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

chrism01 03-05-2013 05:43 PM

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

#!/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.

smallpond 03-05-2013 07:35 PM

First time with Perl?

I think you are confusing opendir with chdir:


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 04:26 PM.