Search code examples
perldirectory

How to go one up folder level using perl?


I'd like to know to search sub-folders if I'm already in the subdirectory.

ex: ..build/clean/test/subfolder <-----

i've already scripted on how to get to test but can't figure out how to go into the subfolder.

The script looks something like this: Directory Handle in Perl Not Working Properly

sub response {
foreach my $arg (@ARGV) {
    print "Investigating $arg directory below:-\n";
    opendir(my $DIR, $arg) or die "You've Passed Invalid Directory as Arguments\n";
    my $size = 0;
    while(my $fileName = readdir $DIR) {
        next if $fileName =~ /^\./;
        my $path = File::Spec->catfile( $arg, $fileName );
        if( -d $path) {
            say "Folder1($arg, $fileName)"
        }
        $size++;
    }
    closedir $DIR;  
    if($size == 0) {
        print "The $arg is an empty directory\n";
    }
}

This is the sub folder

sub Folder1
{
  my $prevPath = shift;
  my $receivedFolder = shift;
  my $realPath = "$prevPath/$receivedFolder";
  my $path = File::Spec->rel2abs($realPath);
  print "$path\n";
  print "$receivedFolder Folder Received\n";
  foreach my $folder (@folder)
  {
    opendir(DIR, $path) or die "You've Passed Invalid Directory as Arguments\n";
        while(my $file = readdir $DIR) {
            next if $file =~ /^\./;
            my $path1 = File::Spec->catfile( $folder, $file );
            if( -d $path1) {
                say "Folder2($folder2, $file)"
   }
      closedir(DIR);
    }

The sub 2 folder

sub Folder2 {
      my $prevPath1 = shift;
      my $receivedFolder1 = shift;
      my $realPath1 = "$prevPath1/$receivedFolder1";
      my $path1 = File::Spec->rel2abs($realPath1);
      print "$path1\n";
      print "$receivedFolder1 Folder Received\n";
      opendir(DIR, $path1) or die "You've Passed Invalid Directory as Arguments\n";
            while(my $file = readdir DIR) {
            print "Current Folder has $file file\n";
           }
     closedir(DIR)
}

I'd like to read the files inside of sub 2 folder. However, i keep going back to the main directory using the sub 2 folder.

my @arg = ('clean');
my @folder = ('logs');

However, inside the build directory there is also a logs folder. It will be re-directed to there instead of the ../clean/test/logs


Solution

  • For working with paths, I'd strongly recommend Path::Tiny.

    use Path::Tiny 'path';
    
    my $path = path "/home/tai/Documents/";
    
    for my $child ( $path->children ) {
       print "$child\n" if $child->is_file;
    }
    
    my $parent = $path->parent;
    print "PARENT: $parent\n";