views:

258

answers:

3

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

For example:

/path/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.

+4  A: 

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/\.[^.]+$//;
rafl
Regarding basename I just read: "This function is provided for compatibility with the Unix shell command basename(1) . It does NOT always return the file name portion of a path as you might expect. To be safe, if you want the file name portion of a path use fileparse()".
Chris
Yes, there's more than one function in the `File::Basename` module, and they all do different things. Pick the one that does what you want. Additionally, similar functionality exists in `File::Spec` as `splitpath`
rafl
+1  A: 

You can do this with simple substitutions:

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

This example assumes that / is the path separator.

eugene y
+2  A: 

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?

Chris