Mak_Thareja
Mak_Thareja

Reputation: 177

How to split a path in perl with full filename?

I want to split a path can anyone help me?

My input is:

$getpath = "/u/project/path/file.name";

I want to split /u/project/path in one variable and file.name in other variable.

Upvotes: 4

Views: 13777

Answers (5)

noonex
noonex

Reputation: 2075

my $f = Mojo::File->new($getpath);
print($f->dirname, "::", $f->basename);

Quick test :

> perl -Mojo -E 'my $f = f("/u/project/path/file.name"); say $f->dirname, "::", $f->basename' 
/u/project/path::file.name

Upvotes: 0

noalac
noalac

Reputation: 186

First of all, there are many perl modules can do what you want, try searching on the CPAN. Second, I suggest using File::Spec module. For example:

use File::Spec;
($volume,$directories,$file) = File::Spec->splitpath( $path );

then $directories will be "/u/project/path", and $file will be "file.name".

File::Spec module is capable of five operating systems: Unix(Linux), Mac, Win32, OS2, VMS. And this module also offers tons of other file operations like catpath, updir, file_name_is_absolute, etc. You don't need to change your codes on different systems.

Ref: File::Spec

Upvotes: 7

ccheneson
ccheneson

Reputation: 49410

File::Basename can help you extract the informations you need (and is part of the core modules)

  my($filename, $directories, $suffix) = fileparse($path);

Upvotes: 11

Vijay
Vijay

Reputation: 67221

my $getpath = "/u/project/path/file.name";
my @arr=split /\//,$getpath;
my $filename=$arr[(scalar(@arr))-1]; #will give you the filename
my $path_no_filename= join "/",@arr[0..(scalar(@arr)-2)]; #will give everything except the filename

Upvotes: 2

mzedeler
mzedeler

Reputation: 4369

my($path, $file) = $getpath =~ m{(.+)/([^/]+)$};

There are nice cross platform modules for this too, see Path::Tiny and File::Spec.

Upvotes: 3

Related Questions