in reply to Getting the filename from full path name ?

See File::Basename. It's a core module, if I'm not mistaken, so you don't even have to install it before using it.

use File::Basename; my $path = '/home/username/public_html/somepath/2004-04-14-0002136'; my $filename = basename($path); print $filename, "\n";


Dave

Replies are listed 'Best First'.
Re: Re: Getting the filename from full path name ?
by demerphq (Chancellor) on Apr 15, 2004 at 12:41 UTC

    Actually File::Basename is to say bluntly a turd. You are much better off using File::Spec and or the functional equivelents in File::Spec::Functions. File::Basename was effectvely deprecated when File::Spec was created (which it was to fix a whole bunch of know problems in the Basename, some outstanding to this day) but it never was marked as such or removed for hysterical porpoises. File::Spec is in the core and it should be used as a general rule for manipulating paths and directories and the like.

    Anyway, the File::Spec::Functions way would be:

    use File::Spec::Functions qw(splitpath); my (undef,undef,$file)=splitpath($path);
    Or:
    use File::Spec; my ($vol,$path,$file)=File::Spec->splitpath($path);

    Also IMO its not worth ignoring the $vol just becuase _your_ OS doesnt have such a concept. If you use File::Spec and assume there will be a volume then everything will work out regardless of where youtr code ends up.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi


      It would be nice if File::Spec had a basename function, too. E.g. sub basename { (splitpath($_[0]))[-1] }. And probably also dirname.

        Why does it need one if it has splitpath() ?


        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi


Re: Re: Getting the filename from full path name ?
by peterr (Scribe) on Apr 15, 2004 at 03:51 UTC
    Hi Dave,

    The module File::Basename worked perfectly, just what I needed.

    Thanks,

    :) Peter