Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective method getting the topmost path element in perl

Tags:

perl

Have

my $path = "//strange/path/";

need get the 1st element with (one) leading slash = /strange or only the / is the $path is empty or contains only slashes.

Currently have two solutions, e.g.:

use 5.014;
use warnings;
use File::Spec;
my $path = "//strange/path/";

#version with File::Spec
my $v1 = "/" . ([grep {/./} File::Spec->splitdir($path)]->[0] //  "");
say $v1;

#regex
my $v2 = $path;
$v2 =~ s{^/*}{};
$v2 =~ s{/.*}{};
$v2 =~ s{^}{/};
say $v2;

I don't like any of them, because the 1.st uses module, and 3 regexes in the second is simply ugly.

Exists more effective || fastest || "nicer" method?

like image 318
cajwine Avatar asked Dec 31 '25 20:12

cajwine


1 Answers

If you want regex, you can try the following "one regex" solution:

use 5.014;
use warnings;
while(<DATA>) {
    chomp;
    my $o = my $n = $_;
    $n =~ s:(^/*)([^/]*)?(/*.*):/$2:;
    say "=$o= =$n=";
}
__DATA__

/
//
strange
strange/
strange/path
/strange
/strange/
/strange/path
//strange
//strange/
//strange/path
//strange//
//strange//
//strange//path

but as above @Moritz Bunkus told - the best is use the standard File::Spec.

like image 135
jm666 Avatar answered Jan 03 '26 13:01

jm666



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!