Reputation: 379
I am trying to extract /temp/bin/usr/
from a variable
$path = /temp/bin/usr/...
using perl. Can someone help me with that ?
Upvotes: 0
Views: 83
Reputation: 2595
If all you need is to remove those '..' in the end there're many ways.
For example:
1)
my $str="/temp/bin/usr/...";
($str) =~ s/\.+$//;
print $str;
2)
my $str="/temp/bin/usr/...";
$str = substr($str, 0, index($str, "."));
print $str;
3)
my $str="/temp/bin/usr/...";
$str = (split /\./, $str)[0];
print $str;
And there're many more!
Upvotes: 1
Reputation: 67930
Use File::Basename
. It is a core module in Perl version 5. From the documentation:
use File::Basename;
($name,$path,$suffix) = fileparse($fullname, @suffixlist);
$name = fileparse($fullname, @suffixlist);
$basename = basename($fullname, @suffixlist);
$dirname = dirname($fullname);
It sounds like dirname($path)
is what you are after.
You may also simply use a regex
$path =~ s/\.+$//;
Upvotes: 3
Reputation: 36282
To extract part of a path, for example, the first three directories, one way is to use the method splitdir
of the module File::Spec
, like:
printf "%s\n", join q|/|, (File::Spec->splitdir( $path ))[0..3];
If you want to remove those dots, use a regular expression that matches them after last slash, like:
$path =~ s|(/)\.+\s*$|$1|;
Upvotes: 1