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?
First of all, the code doesn’t compile.
The message is: Trailing \ in regex m/\/
. Why?
'\\'
is a string containing one character.
Even if you fix the Trailing \ in regex
, there is still a problem :(
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.