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

Dear Masters,
My code below can capture a base name of a file that comes without path
my $file = "somename.out"; my $name = ( split( /\./, $file ) )[0]; print "$file - $name\n"; # This prints "somename" correctly
How can I generalize my regex above when the file name comes with one or more path:
my $file_with_path = "path/somename.out" # or my $file_with_path2 = "path/path2/somename.out"
Such that it yields the same result: somename

---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Capturing Base Name of a File With or Without Path
by monkfan (Curate) on Jan 26, 2006 at 07:04 UTC
    Like this?
    use File::Basename; my $name = basename($file_with_path2,'.out','.some_other_ext'); print "$name\n";
    This also works with file name comes without path. Read the documentation, there are many things you can do with this very useful module.

    Regards,
    Edward
      Yeah, that would do it too.

      *sigh*
      $/ = q#(\w)# ; sub sig { print scalar reverse join ' ', @_ } + sig map { s$\$/\$/$\$2\$1$g && $_ } split( ' ', ",erckha rlPe erthnoa stJu +" );
Re: Capturing Base Name of a File With or Without Path
by chargrill (Parson) on Jan 26, 2006 at 07:10 UTC
    Maybe I should be fully awake and sober for the following, but this should at least get you on your way:
    sub get_basename { my $basename; my $fullname = shift; $fullname =~ m/.*\/(\w+)\.\w+/; $basename = $1; return $basename; }
    If "somename" could contain more than \w provides, then YMMV.
    --chargrill
    $/ = q#(\w)# ; sub sig { print scalar reverse join ' ', @_ } + sig map { s$\$/\$/$\$2\$1$g && $_ } split( ' ', ",erckha rlPe erthnoa stJu +" );
Re: Capturing Base Name of a File With or Without Path
by smokemachine (Hermit) on Jan 26, 2006 at 10:10 UTC
    Just use $1 if found the regex;
    sub get_basename {return $1 if shift =~ /(\w+)(\.\w+)?$/}