Dcoder
Dcoder

Reputation: 379

How to extract path from a variable with additional characters in perl

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

Answers (3)

varnie
varnie

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

TLP
TLP

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

Birei
Birei

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

Related Questions