本文介绍了如何将完整路径分成目录和文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$a = '/etc/init/tree/errrocodr/a.txt'

我想将 /etc/init/tree/errrocodr/ 提取到 $dir 并将 a.txt 提取到 $file.我该怎么做?

I want to extract /etc/init/tree/errrocodr/ to $dir and a.txt to $file. How can I do that?

(编者注:最初的问题假定您需要一个正则表达式.)

推荐答案

只需使用 Basename:

use File::Basename;
$fullspec = "/etc/init/tree/errrocodr/a.txt";

my($file, $dir, $ext) = fileparse($fullspec);
print "Directory: " . $dir . "\n";
print "File:      " . $file . "\n";
print "Suffix:    " . $ext . "\n\n";

my($file, $dir, $ext) = fileparse($fullspec, qr/\.[^.]*/);
print "Directory: " . $dir . "\n";
print "File:      " . $file . "\n";
print "Suffix:    " . $ext . "\n";

您可以看到这会返回您请求的结果,但它也能够捕获扩展名(在上面的后一部分中):

You can see this returning the results you requested but it's also capable of capturing the extensions as well (in the latter section above):

Directory: /etc/init/tree/errrocodr/
File:      a.txt
Suffix:

Directory: /etc/init/tree/errrocodr/
File:      a
Suffix:    .txt

这篇关于如何将完整路径分成目录和文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:27