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

What is the best way to isolate just the filename from a string containing the full path to a file?

$s = "/home/virtual/path/to/www/some/directory/filename.txt";

I would prefer to have the file extension (.txt in this case) removed as well.

Thank you so much.

Replies are listed 'Best First'.
Re: Isolating a file name
by liverpole (Monsignor) on Feb 04, 2006 at 19:50 UTC
    You can do it with File::Basename, which is in the core distribution for Perl:
    use File::Basename; my $s = "/home/virtual/path/to/www/some/directory/filename.txt"; my $fname = basename($s);
    To get rid of the file extension, use fileparse (from the same module).   You can use the command perldoc File::Basename for more details.

    Update:  As helphand points out, you can also supply the extension (or a list of extensions) to strip, to basename.  Of course, you could also just use a regex to strip any extension afterwards, such as:

    $fname =~ s/\.[^\.]*$//;

    @ARGV=split//,"/:L"; map{print substr crypt($_,ord pop),2,3}qw"PerlyouC READPIPE provides"
Re: Isolating a file name
by helphand (Pilgrim) on Feb 04, 2006 at 19:46 UTC
    use strict; use warnings; use File::Basename; my $s = "/home/virtual/path/to/www/some/directory/filename.txt"; print basename($s,'.txt') . "\n";

    Scott

      It occurs to me that if you don't know the extension in advance, this approach would be more flexible.

      use strict; use warnings; use File::Basename; my $s = "/home/virtual/path/to/www/some/directory/filename.txt"; my ($base,$path,$ext) = fileparse($s,'\..*'); print "$base\n";

      Scott

Re: Isolating a file name
by pro7agon (Initiate) on Feb 04, 2006 at 20:14 UTC
    use strict;

    print $1 if ($s =~ /.(\w+).(\w+)$/g);
A reply falls below the community's threshold of quality. You may see it by logging in.