Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a path that I just need the file name on a Windows NT workstation:

G:\\anyDir\myFileName.doc
\\\InforServer\data.xls
C:\\nextName.doc
C:\\perl\bin\file.pl

Please advise how I can fetch the file name from these listings so I get:
myFilename.doc
data.xls
nextName.doc
file.pl

My attempt not working:
$name = s/\w\:\\\*//; print $name;

Replies are listed 'Best First'.
Re: Fetch filename only
by sweetblood (Prior) on Feb 10, 2006 at 19:04 UTC
Re: Fetch filename only
by serf (Chaplain) on Feb 10, 2006 at 19:14 UTC
    File::Basename is the most robust and portable way to do this.

    If you still wanted to do it via regexp instead you could do something like:

    $name =~ s/^.*\\//;
    (which says remove any characters up to and including the last backslash)

    NB(1): This uses =~, not = as you have in your example.

    In your example, by using \w\:\\ you were trying to cater for the ones which start with a drive letter [CG]:\,
    but were forgetting about \\\InforServer\data.xls which presumably has a UNC pathname, starting with \\

    You could have done the "drive letter" ones with:

    $name =~ s/^\w:\\.*\\//; (Note: The : doesn't need escaping here)

    or better:

    $name =~ s/^[A-Z]:\\.*\\//;
    NB(2): Think about the fact that the path will have word characters and spaces and backslashes in it,

    Also all of these regexps *have* to finish with a \\ to terminate the match, otherwise the greediness will go on and eat up the filename as well.

      Thanks alot for the quick responses.
      We have Perl 5.8 on our server and I assume File::Basename is a standard module with that version?

      If not I will use your req expression but right now I am testing it on my workstation and not sure if we have File::Basename on our server if it is not a standard module.
Re: Fetch filename only
by hesco (Deacon) on Feb 10, 2006 at 19:15 UTC
    Or without the added dependency, try this untested string substitution instead:
    $fn = $fqfn = $_; # fully qualified file name $fn ~= s/^.*\\//; # let the greediness of regex's find # the last backslash for you print "\n$fqfn\n$fn\n";
    -- Hugh
Re: Fetch filename only
by smokemachine (Hermit) on Feb 11, 2006 at 04:48 UTC