perlfileparse

perl - File::Basename->fileparse returns "File::Basename"


For some reason my code is doing this wierd thing where fileparse only prints (literally) File::Basename

 use strict;
 use warnings 'all';
 use File::Basename;

 ...

 my $fileName = File::Basename->fileparse($filePath);
 print("$filePath\n");
 print("$fileName\n");

And output is:

a/b/c/d.bin
File::Basename

What did I do wrong?


Solution

  • The fileparse is not a method; it is a function. This function is exported by default, so you actually want to do

    use File::Basename;
    my $fileName = fileparse($filePath);
    

    You have used is as a method call. Here File::Basename->fileparse($filePath) is equivalent to

    fileparse("File::Basename", $filePath)
    

    because in a method invocation, the invocant (usually an object; here the package name) becomes the first argument. This is wrong, as it treats "File::Basename" as the path to parse, and the following arguments as a list of valid suffixes.

    If you want to use the fileparse function without exporting it to your namespace, you could

    use File::Basename (); # note empty parens that supress the import
    File::Basename::fileparse(...); # use fully qualified name