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

Hello!
Can you please help me on how I can select only the main name from a series of files that have the same ending? E.g:
/home/username/myfiles/split_files/file1.top /home/username/myfiles/split_files/file2.top ...

I basically have this line in my script:
my $infile = $ARGV[0];

and I want to add a line that extracts only the 'core' part of the name before the ending, like file1, file2 etc, regardless of what is the long path before that. I believe is something to do with basename perhaps?

Replies are listed 'Best First'.
Re: Extract main name of file
by Your Mother (Archbishop) on Mar 03, 2022 at 02:27 UTC

    I am a big fan of Path::Tiny. I recommend it. It helps file handling at multiple levels.

    use 5.10.0; use strictures; use Path::Tiny; my $dir = path( shift || "./" ); $dir->is_dir or die "$dir is not a directory!\n"; for my $file ( grep -f, $dir->children ) { say $file->absolute; say " -> ", $file->basename; }

    Update: made the code more generic to either take a dir or use the current dir and report on properness of argument and only list child files.

Re: Extract main name of file
by Discipulus (Canon) on Mar 03, 2022 at 07:53 UTC
    Hello,

    Also core module File::Spec and notably the splitpath function can be useful

    ($volume,$directories,$file) = File::Spec->splitpath( $path );

    Then you need to manage the extension of the file with a regex or as you have done already.

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Extract main name of file
by Anonymous Monk on Mar 02, 2022 at 22:46 UTC
    Ah, found it!
    use File::Basename; my $infile=$ARGV[0]; my $filename = basename($infile, ".top");
    :)
Re: Extract main name of file
by siberia-man (Friar) on Mar 03, 2022 at 10:51 UTC
    Windows and Unix compatible way to extract filename.
    my $ME = $0; $ME =~ s/.*[\\\/]//; # $ME =~ s/\.[^.]+$//;
    The extension is not removed, because the script placed in $PATH is still invoked by the name and extension. Another reason to leave the extension - its definition is weak in all operating systems. However sometimes you need the bare filename (for example script.pl requires script.conf). To cover this requirement uncomment the last line above. However if you need do it in mass - better choice to use modules. For example, already suggested by other responders.
A reply falls below the community's threshold of quality. You may see it by logging in.