[plug] Cutting Strings in Perl

Craig Ringer craig at postnewspapers.com.au
Thu Jan 15 13:02:30 WST 2004


Tim White wrote:
> I have a string in perl in the below format.
> C:\dir1\dir2\filename.ext
> (It may have more than 1 extentsion)
> What I wish to do is just get the file name in a number of formats.
> I would like out put in the below formats
> filename
> filename.ext
> Could anybody please help me as I don't under stand regex and all the web sites 
> I could find weren't very helpfully.

man perlre
or
perldoc perlre

off the top of my head, these should work. Read the regex and figure out 
what it does:

$filename =~ m/\\([^\\]+)(\.[^\\]+)$/;
$string1 = $1;
$string2 = "$1$2";

alternately, you could cheat and use basename(1) from a shell escape:

$string2 = `basename $filename`

I'll leave it to you to figure out how to cut off the extension after that.

Note: If you can make safe assumptions like '.ext' is always 4 chars, 
it's easier - but that may not always be true, so it's generally safer 
to do a general solution.

Craig Ringer




More information about the plug mailing list