简体   繁体   English

如何使用Perl获取文件的dirname?

[英]How do I get the dirname of a file with Perl?

In my perl script, I have the param $FILE=/etc/sysconfig/network 在我的perl脚本中,我有param $FILE=/etc/sysconfig/network

in which way (in perl) I can cut only the directory and put the directory in $DIR param 以哪种方式(在perl中)我只能剪切目录并将目录放在$ DIR param中

in order to get: 为了得到:

$DIR=/etc/sysconfig

(like dirname /etc/sysconfig/network in shell script)

Watch out! 小心! dirname() is deliberately dumb to emulate the dirname shell command. dirname()故意愚蠢地模仿dirname shell命令。 It is not so much "give me the directory part of this file path" as "give me all but the last part of this path". 它并不是“给我这个文件路径的目录部分”作为“除了这条路径的最后一部分之外给我所有”。 Why is that important? 为什么这很重要?

my $dir = "/foo/bar/";   # obviously a directory
print dirname($dir);     # prints /foo

This is fine, just so long as you realize that dirname does not return the dirname. 这很好,只要你意识到dirname没有返回dirname。

If you want the above to return /foo/bar/ you're better off using File::Spec. 如果你想让上面的内容返回/foo/bar/你最好使用File :: Spec。

use File::Spec;
my($vol,$dir,$file) = File::Spec->splitpath($path);
use File::Basename;

($name,$path,$suffix) = fileparse($fullname,@suffixlist);

$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$dirname  = dirname($fullname);

Read more about File::Basename in perldoc. 在perldoc中阅读有关File :: Basename的更多信息。

Use the File::Basename core module: 使用File :: Basename核心模块:

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

my $FILE = '/etc/sysconfig/network';
my $DIR = dirname($FILE);
print $DIR, "\n";

This prints out: 打印出:

/etc/sysconfig 在/ etc / SYSCONFIG

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM