Reputation: 113
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?
Upvotes: 0
Views: 52
Reputation: 174696
Try this regex.
$path =~ s/^(.*)\/.*/\1/
Group index 1 contains the string you want.
Upvotes: 0
Reputation: 902
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;
Upvotes: 2
Reputation: 35198
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);
Upvotes: 4