Just when you think you know everything about Perl, something silly rises up and shows you have ignorant you really are.
How many times have you written code similar to this?
my $filename = "/path/to/file.txt";
my @dir_parts = split('/', $filename);
my $file = pop( @dir_parts );
my $path = join('/', @dir_parts );
or
my ($name) = $filename =~ s/\/(.*?)$/o;
While I knew about the existance of File::Basename, the last time I looked at it I don't believe it was part of Perl Core. I should have suspected, but now it is a standard Perl module that makes this trivial:
use File::Basename;
# Retrieve just the filename
my $filename_only = basename($filename);
# Get just the path in this filename
my $path_only = dirname($filename);
You can get even fancier with the fileparse() function provided in
this module.
my ($base, $path, $suffix) = fileparse( $filename );
Would yield the filename only in $base, the path in $path, and
nothing in $suffix. This is because we did not provide a regular
expression to match on.
If we instead used:
my ($base, $path, $suffix) = fileparse( $filename, qr{\.txt} );
And we ran it against $filename = '/home/frank/test.txt' and
$filename2 = '/home/frank/test.doc' it would give us:
Base: test
Path: /home/frank
Type: .txt
and
Base: test.doc
Path: /home/frank
Type:
If the filename give to fileparse() does not match, it is not
stripped from the basename.
It just goes to show that no matter how long you've been using Perl, or how much you think you know, there is always something out there you could be learning.