0

Suppose I have a

$path = "/usr/local/bin/mybinary"

how can I use regular expressions to get $regex = "/usr/local/bin".

I am new to regex. I tried as follows:

$regex =~ s/w+/.*\// 

This doesnt work. How can I do what I want?

3 Answers 3

4

Using a regex:

$path = "/usr/local/bin/mybinary"

my $parent = $path =~ m{(.*)/} ? $1 : warn "Unrecognized";

However, I would recommend using File::Basename or similar module:

use File::Basename;

my $dir = dirname($path);
Sign up to request clarification or add additional context in comments.

2 Comments

This works ! Why do we use the warn "Unrecognized" after the ':'? Is it mandatory?
You should always check to make sure a regular expression actually matched before using a capture group.
2

Try this code as shown below:

use File::Basename;

my $path = "/usr/local/bin/mybinary";
my $filename = basename($path);
my $dir = dirname($path);

Besides File::Basename, there's also Path::Class, which can be handy for more complex operations, particularly when dealing with directories, or cross-platform/filesystem operations. It's probably overkill in this case, but might be worth knowing about.

use Path::Class;

my $file = file( "/usr/local/bin/mybinary" );
my $filename = $file->basename;

1 Comment

There is also Path::Tiny.
0

Try this regex.

$path =~ s/^(.*)\/.*/\1/

Group index 1 contains the string you want.

1 Comment

It's better to use one of the file path processing modules than a regex to process paths.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.