如何在perl中将文件名和文件路径与包含完整文件路径的字符串分开

时间:2013-03-28 07:26:54

标签: perl

我有一个perl程序,其中有一个变量,其值是文件的完整路径。

例如:

$FullPath = "C:\sample\file.txt";

我想提取$ FileName变量中的文件名(file.txt)和C:\sample\变量中的路径(FilePath)。

任何人都可以通过示例代码帮助我这样做。

谢谢

2 个答案:

答案 0 :(得分:3)

use File::Basename qw( fileparse );
my ($fname, $dir) = fileparse($FullPath);

请注意,您的$FullPath不包含C:\sample\file.txt。要做到这一点,你需要

my $FullPath = "C:\\sample\\file.txt";

my $FullPath = 'C:\sample\file.txt';

始终使用use strict; use warnings;!由于无意义"\s",它会发出警告。


要解析任何计算机上的Windows路径,可以使用以下命令:

use Path::Class qw( foreign_file );
my $file = foreign_file('Win32', $FullPath);
my $fname = $file->basename();
my $dir   = $file->dir();

答案 1 :(得分:0)

我建议您使用splitpath中的File::Spec::Functions。此函数将卷,目录和文件名作为三个单独的值返回。

下面的代码将这些值放入一个数组中,然后删除第二个(目录)元素并将其附加到第一个元素,在@path中根据需要提供完整路径和文件名。

use strict;
use warnings;

use File::Spec::Functions 'splitpath';

my $full_path = 'C:\sample\file.txt';
my @path = splitpath $full_path;
$path[0] .= splice @path, 1, 1;

print "$_\n" for @path;

<强>输出

C:\sample\
file.txt
相关问题