user1602400
user1602400

Reputation: 3

How to get the directory in a path in perl

I have a directory path:

my $temp = "/a/b/c/d";
my $upDirectory = dirname( $temp );

This returns "/a/b/c". But I need just "c". I have to compare it with a string to determine if it is the right directory.

Is there a way other than split on "/"? I do not want to use this. The Perl code has to be used on multiple platforms. Can splitdir help?

Upvotes: 0

Views: 486

Answers (2)

daxim
daxim

Reputation: 39158

Obligatory Path::Class solution:

use Path::Class qw(dir);
dir('/a/b/c/d')->parent->dir_list(-1)
# expression returns 'c'

Upvotes: 1

Ask Bjørn Hansen
Ask Bjørn Hansen

Reputation: 6953

There are, of course, many ways to do it but if your main concern is portability to other platforms then File::Spec is probably a reasonable bet. Look for splitpath and splitdir.

Upvotes: 5

Related Questions