perl

Perl: How File::Spec->canonpath($path) works


What is this method doing?

I simply don't understand it's purpose, and the explanation in perldoc is not helping me.

Now I need to update a Script that uses this method, so it would be good to understand what it is doing.

Is there a simple tutorial to understand the method?


Solution

  • A call to canonpath returns the canonical path that is equivalent to the passed parameter. That means it will

    This is best demonstrated with a Windows path like

    C:/a/b/../c///d/.//
    

    This Perl code

    use strict;
    use warnings;
    use feature 'say';
    
    use File::Spec;
    
    say File::Spec->canonpath('C:/a/b/../c///d/.//');
    

    output

    C:\a\c\d
    

    Unfortunately I can't explain the code you show

    my $dir  = File::Spec->curdir();
    my $path = File::Spec->canonpath($dir);
    

    because the curdir method returns . on Windows and Linux systems, and canonpath leaves this unchanged. If you wanted to discover the absolute path to the current directory then you would use

    my $path = File::Spec->rel2abs(File::Spec->curdir());
    

    However this is better done with the Cwd module like this

    use Cwd ();
    
    my $path = Cwd::cwd;