On 4/26/07, Nishi <[EMAIL PROTECTED]> wrote:
Rob:


On 4/25/07, Rob Dixon <[EMAIL PROTECTED]> wrote:
>
> Nishi wrote:
> >
> > What is the equivalent of basename? Ie if I dont want to use basename
> > package to get the filename off a path, what reg expr can i use in perl?
> >
> > Would this work --
> > my $fileName=$path =~ /.*\/(.+)$/;
>
> Why don't you try it?!
>
> It wouldn't work because $fileName would end up with either a true or a
> false value depending on whether the regex matched. To get the captured
> string put the regex in list context:
>
>   my ($fileName) = $path =~ /.*\/(.+)$/;
>
> But it would still fail if there was no slash in the $path string. You
> may want to use the slightly simpler
>
>   my ($name) = $path =~ m|([^/]+)$|;


I tried it, but somehow doesnt work for me, printing $name returns me the
entire string such as C:\temp\abc\abc.txt and not abc.txt.
Am I missing something?

which just grabs all the characters at the end of the string that aren't
> slashes, and works whether or not there is a path as well as a file name
> in the string.
>
> Cheers,
>
> Rob
>
>
>

File::Basename (which is part of core Perl) is the bst solution to
your problem.  If it doesn't work then Perl is not installed correctly
and you may have other problems.

But, if you insist on not using it then use a sexeger*:

#!/usr/bin/perl

use strict;
use warnings;

my @files = (
       '/usr/bin/perl',
       'c:\Program Files\Perl\perl.exe'
);

for my $fullpath (@files) {
       my $filename = scalar reverse(reverse($fullpath) =~ m{^(.*?)[\\/]});
       print "$filename\n";
}


* http://japhy.perlmonk.org/sexeger/sexeger.html

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to