user2988540
user2988540

Reputation: 11

How to split current directory

I need to get the trailing part of the current directory into a variable. I can do a:

use Cwd;
my $dir = getcwd;

to get the full path of: usr\bjm\scPDB_entries\4dpt, but what I really need is the 4dpt to be split out from the rest of the path.

Upvotes: 1

Views: 248

Answers (2)

Borodin
Borodin

Reputation: 126722

It is best to use File::Spec, especially if the code is required to work across platforms. The documentation for File::Basename says this.

If your concern is just parsing paths it is safer to use File::Spec's splitpath() and splitdir() methods.

This program does what you ask

use strict;
use warnings;

use File::Spec;

my $cwd = File::Spec->rel2abs;
my @path = File::Spec->splitdir($cwd);
my $dir = $path[-1];
print $dir;

It long-winded mainly because of the object-oriented nature of File::Spec. The helper module File::Spec::Functions allows you to make it more concise, by importing the class methods as local subroutines.

use strict;
use warnings;

use File::Spec::Functions qw/ rel2abs splitdir /;

my $dir = (splitdir(rel2abs))[-1];
print $dir;

Upvotes: 4

toolic
toolic

Reputation: 62037

File::Basename

use File::Basename qw(basename);
print basename($dir), "\n";

Upvotes: 5

Related Questions