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

Hi All, I have a script that has the current path as a variable. I need to get just the folder name from the path. Here is an example.
The directory: "c:/mail/test2" - should produce "test2"

The directory: "c:/mail" - should produce "mail" and so on and so forth.

Is this best handled with Regex? and what would the regex look like.

Thanks

Replies are listed 'Best First'.
Re: get folder name only
by dmorelli (Scribe) on Mar 09, 2005 at 17:39 UTC
    There's actually a "core" module for parsing paths, see perldoc File::Basename

    #! /usr/bin/perl -w use strict; use File::Basename; print dirname 'c:/mail/test2';
      Something was bugging me about this, basename returns nothing if the path ends with a dir separator. This will deal with that:

      #! /usr/bin/perl -w use strict; use File::Basename; # Test data my @dirs = ( 'c:/mail/test2', 'c:/mail', 'c:/mail/test2/', 'c:/mail/', ); foreach (@dirs) { print "before: $_ "; # Strip off the trailing / # Warning: may not be platform independent s|/$||; print "after: " . basename $_ . $/; }
Re: get folder name only
by davido (Cardinal) on Mar 09, 2005 at 17:37 UTC

    If using a regexp...:

    if( $string =~ m![/\\]([^/\\]+)$! ) { print $1, "\n"; }

    This works as long as you're dealing only with paths where there isn't a trailing filename. And of course it would run amok if the path didn't start with either a / or a \, or if a directory name allowed embedded / or \ characters. :) caviet lector.


    Dave

Re: get folder name only
by RazorbladeBidet (Friar) on Mar 09, 2005 at 17:41 UTC