tags:

views:

78

answers:

4
$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.)

+8  A: 

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
paxdiablo
Or alternatively, have a look at File::Spec->splitpath(), which separates out the volume as well (if you happen to be on a platform that has such a thing). The advantage of either package is that they are standard and portable.
Mike Ellery
+4  A: 

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/
ennuikiller
+1, but IMHO should not use the variable `$a` in your example even if the OP mistakenly did. It is used for `sort`
drewk
A: 

Maybe this will work:

@^(.+/)/([^/]+)$@
killer_PL
A: 

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.

leonbloy