All entries

Paths

29 Nov 2013
Эта же задача по-русски: здесь.

Eric wrote a function to calculate depth of path in a filesystem.

=head2 path_depth

Receives an absolute filepath, returns its depth.
Supports Unix-style and Windows-style paths.

/, a:\ --> 0
/bin, c:\program files --> 1
/etc/hosts --> 2
C:\WINDOWS\system32\drivers\etc\hosts --> 5
                                                          
=cut                                                      
                                                          
sub path_depth
{   
    my $path = shift;
    if ( $path =~ m{^/} ){
        # Unix
        $path =~ s!/+$!!g;
        $path =~ s!//+!/!g;
        return scalar(split '/', $path) - 1;
    } elsif ( $path =~ m{^.:} ) {
        # Windows
        $path =~ s!\\+$!!g;
        $path =~ s!\\+!\\!g;
        return scalar(split '\\', $path) - 1;
    } else {
        die "unknown format";
    }
}

Is everything OK here?

Подсказка

Show

First of all, the code doesn’t compile.

Подсказка-2

Show

The message is: Trailing \ in regex m/\/. Why?

Подсказка-3

Show

'\\' is a string containing one character.

Подсказка-4

Show

Even if you fix the Trailing \ in regex, there is still a problem :(

Разоблачение

Show

There is an issue with split in Windows part of the code. It gets the string '\\' as first parameter, and the string is being interpolated into regex. So it becomes:

return scalar(split m{\}, $path) - 1;

which, of course, is incorrect.

It is a good practice to always pass an explicit regex as a first parameter for split: split m{\\}, $path.

Besides, the function returns incorrect result for the root directory in Unix: path_depth('/') gives -1 instead of 0.