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

Hello Monks,

I have filenames like:

$file1 = C:\test\abc.txt $file2 = C:\test\file2.txt $file3 = P:\cool\file3.txt
I want to basically remove the path for each variable.

Hence,

$file1 = abc.txt $file2 = files2.txt
etc...

Please suggest how to grab everything till the last "\" and substitute it for nothing.

I was thinking this:

$file =~ s/.*\\?//
Please advice.

Updated Steve_p - added code tags

Replies are listed 'Best First'.
Re: substituting file names
by Transient (Hermit) on May 06, 2005 at 20:40 UTC
      What Transient said...
Re: substituting file names
by gopalr (Priest) on May 07, 2005 at 09:16 UTC

    use File::Basename to do this job

    use File::Basename; $file1 = 'C:\test\abc.txt'; $file2 = 'C:\test\file2.txt'; $file3 = 'P:\cool\file3.txt'; $file1=basename($file1); $file2=basename($file2); $file3=basename($file3); print "$file1\n"; print "$file2\n"; print "$file3\n";

    Output

    abc.txt file2.txt file3.txt
Re: substituting file names
by TedPride (Priest) on May 06, 2005 at 22:46 UTC
    use strict; use warnings; my $file1 = 'C:\test\abc.txt'; my $file2 = 'C:\test\file2.txt'; my $file3 = 'P:\cool\file3.txt'; fname($file1, $file2, $file3); print $file1; sub fname { s/.*\\// for @_; }
Re: substituting file names
by perlsen (Chaplain) on May 07, 2005 at 09:11 UTC
    hi just Try this
    $file =~ s#^.*\\(.*)#$1#gsi;