Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Get Parent Folder Name

Tags:

perl

What is the solution to get the name of the parent directory using File::Find. I know how to get only the filename or only the directory path but I don't know how to do this for the last containing directory.

For example, if the directory is /dir_1/dir_2/dir_3/.../dir_n/*.txt I need to get the 'dir_n' name.

use strict;
use warnings;
use File::Find;

my $dir = "some_path";

find(\&file_handle, $dir); 
sub file_handle {
    /\.txt$/ or return;
    my $fd = $File::Find::dir;
    my $fn = $File::Find::name;
    # ...
}
like image 425
thebourneid Avatar asked Nov 30 '10 21:11

thebourneid


2 Answers

Given the directory path, you then apply File::Basename (another core module) to the path to obtain the last portion of the directory.

use strict;
use warnings;
use File::Find;
use File::Basename;

my $dir = "some_path";

find(\&file_handle, $dir); 
sub file_handle {
    /\.txt$/ or return;
    my $fd = $File::Find::dir;
    my $fn = $File::Find::name;
    my $dir = basename($fd);
    # ....
}
like image 152
Jonathan Leffler Avatar answered Oct 06 '22 20:10

Jonathan Leffler


#!/usr/local/bin/perl -w

use strict;
use File::Basename;
use Cwd 'abs_path';

my $f = "../some/path/to/this_directory/and_filename";  
my $d = basename(dirname(abs_path($f)));
say $d;

returns "this_directory"

like image 21
margaret Avatar answered Oct 06 '22 20:10

margaret