Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I seperate a filename from its extension so I can use both

Status
Not open for further replies.

teka2112

Technical User
Feb 5, 2003
14
0
0
US
I need to take a standard filename:

myfilename.ext

and seperate the filename from the extension and be able to use both in my code. im new to perl - have written only a few scripts.

so, i would like to end up with (somehow)

$filename = myfilename
$ext = ext

thanks
 
You could use a regex and do something like:
[tt]my ($filename, $ext) = ($file =~ /^(.*?)\.?([^\.]*)$/);[/tt]

The [tt](.*?)[/tt] matches all characters in a non-greedy way and will group it as $1 (or the first variable in a list assignment.) If you just used [tt](.*)[/tt] it would match the entire string in this case, and you'd get the extension in there, too.

[tt]\.?[/tt] matches a ".", optionally. This will allow you to have [tt]$file="file";[/tt] and get the results: [tt]$filename = "file"; $ext = "";[/tt]

[tt]([^\.]*)$[/tt] matches any number of non "." characters at the end of the string and groups it as $2 (or second variable in the list assignment.)
 
Even simpler;

($file, $ext) = split(/\./, $inputname);

or
($file, $ext) = split(/\./, "myfile.ext");
 
what.if.this.was.your.file.name.txt? ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
actually - it is possible that the filename could be in parts delimited by a .

file.name.ext

so what would the above example do?

$file eq file
$ext eq name ????

or

$file eq name
$ext eq ext ?????

 
My regex example would have [tt]$file eq 'file.name'[/tt] and [tt]$ext eq 'ext'[/tt].

I'd personally consider this correct behavior.
 
I thank you all for your input :)

rosenk, I went with your idea and it worked perfectly and behaves exactly as I need - thanks very much!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top