$a = '/etc/init/tree/errrocodr/a.txt'
I want to extract /etc/init/tree/errrocodr/
to $dir
and a.txt
to $file
. How can I do that?
(Editor's note: the original question presumed that you needed a regular expression for that.)
$a = '/etc/init/tree/errrocodr/a.txt'
I want to extract /etc/init/tree/errrocodr/
to $dir
and a.txt
to $file
. How can I do that?
(Editor's note: the original question presumed that you needed a regular expression for that.)
Why are you using a regex at all? Just use Basename:
use File::Basename;
$fullspec = "/etc/init/tree/errrocodr/a.txt";
my($file, $dir, $ext) = fileparse($fullspec);
print "Directory: " . $dir . "\n";
print "File: " . $file . "\n";
print "Suffix: " . $ext . "\n\n";
my($file, $dir, $ext) = fileparse($fullspec, qr/\.[^.]*/);
print "Directory: " . $dir . "\n";
print "File: " . $file . "\n";
print "Suffix: " . $ext . "\n";
You can see this returning the results you requested but it's also capable of capturing the extensions as well (in the latter section above):
Directory: /etc/init/tree/errrocodr/
File: a.txt
Suffix:
Directory: /etc/init/tree/errrocodr/
File: a
Suffix: .txt
you don't need a regex for this, you can use dirname():
use File::Basename;
my $dir = dirname($a)
however this regex will work:
my $dir = $a
$dir =~ s/(.*)\/.*$/$1/
For example:
$a =~ m#^(.*?)([^/]*)$#;
($dir,$file) = ($1,$2);
But, as other said, it's better to just use Basename
for this.
And, BTW, better avoid $a
and $b
as variable names, as they have a special meaning, for sort
function.