开发者

Remove file extension and path from a string in Perl

I want to obtain a file name without its path (if it is part of the string) and also the extension.

For example:

/p开发者_Go百科ath/to/file/fileName.txt     # results in "fileName"
fileName.txt                   # results in "fileName"
/path/to/file/file.with.periods.txt    # results in "file.with.periods" 

So basically, I want to remove anything before and including the last "/" if present and also the last "." along with any meta characters after it.

Sorry for such a novice question, but I am new to perl.


For portably getting the basename of a file given a full path, I'd recommend the File::Basename module, which is part of the core.

To do heuristics on file extensions I'd go for a regular expression like

(my $without_extension = $basename) =~ s/\.[^.]+$//;


Although others have responded, after reading a bit on basename per rafl's answer:

($file,$dir,$ext) = fileparse($fullname, qr/\.[^.]*/);
# dir="/usr/local/src/" file="perl-5.6.1.tar" ext=".gz"

Seems to solve the problem in one line.

Are there any problems related with this, opposed to the other solutions?


Assuming that the path separator is '/', you can do it with a pair of substitutions:

$name =~ s{^.*/}{};     # remove the leading path  
$name =~ s{\.[^.]+$}{}; # remove the extension

You can also write that as a single substitution:

$name =~ s{^.*/|\.[^.]+$}{}g;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜