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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With