tags:

views:

89

answers:

3

Hello, Suppose I have a path in a string called '/home/user/directory/HelloWorld.txt'. I would like to remove the HelloWorld.txt, and end up with '/home/user/directory'. What regex would I need.

A: 

This:

$string =~ s:(.*)/[^/]*$:$1:;
Kinopiko
This might work, if you're on a *nix environment. Other OSes this will fail. If this is for anything other than homework, do not use a regex. See [John Feminella's answer](http://stackoverflow.com/questions/2582132/given-the-full-path-to-a-file-how-do-i-get-just-the-path-without-the-filename/2582147#2582147) instead.
Robert P
+15  A: 

Don't use a regex. Instead, use File::Basename, which can handle all the special cases.

use File::Basename;

dirname("/foo/bar/baz/quux.txt"); --> "/foo/bar/baz"
John Feminella
And File::Basename will handle Windows file names where the average regex won't.
Jonathan Leffler
From the documentation you linked to:"`dirname` This function is provided for compatibility with the Unix shell command dirname(1) and has inherited some of its quirks. In spite of its name it does NOT always return the directory name as you might expect. To be safe, if you want the directory name of a path use fileparse()."
Kinopiko
@Kinopiko: It'll work for all reasonable cases. But yes, fileparse is just as good.
John Feminella
Except that the author of the question needs another function, basename(), not dirname(). Basename() will return the file name (rather than the path to parent).
kirillka
@kirillka : Unless I'm misunderstanding something, he wants just the path. "I would like to remove the HelloWorld.txt, and end up with '/home/user/directory'."
John Feminella
And `dirname` will handle VMS where the filename format is DISK$SOMETHING:[DIR.DIR]FILE.EXT
justintime
+1  A: 

split on "/", remove last element and join them back.

$path='/home/user/directory/HelloWorld.txt';
@s = split /\// ,$path;
pop(@s);
print join("/",@s);
ghostdog74