Extract file extension: Difference between revisions

Tcl implementation added
(Add Racket)
(Tcl implementation added)
Line 219:
file ext= [null] for file name=file.odd_one
</pre>
 
=={{header|Tcl}==
 
Tcl's built in [http://wiki.tcl.tk/10072 file extension] command already almost knows how to do this, except it accepts any character after the dot. Just for fun, we'll enhance the builtin with a new subcommand with the limitation specified for this problem.
 
<lang Tcl>proc assert {expr} { ;# for "static" assertions that throw nice errors
if {![uplevel 1 [list expr $expr]]} {
set msg "{$expr}"
catch {append msg " {[uplevel 1 [list subst -noc $expr]]}"}
tailcall throw {ASSERT ERROR} $msg
}
}
 
proc file_ext {file} {
set res ""
regexp {(\.[a-z0-9]+)$} $file -> res
return $res
}
 
set map [namespace ensemble configure file -map]
dict set map ext ::file_ext
namespace ensemble configure file -map $map
 
# and a test:
foreach {file ext} {
picture.jpg .jpg
http://mywebsite.com/picture/image.png .png
myuniquefile.longextension .longextension
IAmAFileWithoutExtension ""
/path/to.my/file ""
file.odd_one ""
} {
set res ""
assert {[file ext $file] eq $ext}
}</lang>
Anonymous user