On 07/08/2010 10:44 AM, Michael Wild wrote:
On 8. Jul, 2010, at 10:35 , Johny wrote:
I am trying to write a cmake function which imitates the functionality of wc -l
for unix. However i can't seem to be able to figure out how to store the result
into the variable which is passed to the function.
function (wcl fileName lines)
file(READ ${fileName} fileData)
if(fileData)
string(REGEX MATCHALL "\n" lines ${fileData})
list(LENGTH lines lines)
endif(fileData)
endfunction()
i call the function as
wcl (${fileName} fileLen)
and printing it gives no output
message("${fileLen}")
What am i doing wrong ?
Regards
Johny
A function creates a new scope, so you need to explicitly set the variable in
the callers scope. Do something like this (it is usual for the output variable
name to be the first argument:
function (wcl nLinesVar fileName)
file(READ ${fileName} fileData)
if(fileData)
string(REGEX MATCHALL "\n" nLines ${fileData})
list(LENGTH nLines nLines)
set(${nLinesVar} ${nLines} PARENT_SCOPE)
else()
set(${nLinesVar} -1 PARENT_SCOPE)
endif()
endfunction()
wcl (fileLen ${fileName})
However, I'm not sure whether counting \n is a good idea (after all, at some
point you might encounter a file with Windows or Mac line endings, or a file
with a missing terminating \n.
Michael
It works like a charm . Thanks!
I've also modified it a bit for Mac and Windows compatibility but not
for files that don't end in newlines since all the files i'm using
always do terminate with newlines. Here's the modified function
function (wcl _nLinesVar fileName)
file(READ ${fileName} fileData)
if(fileData)
if(WIN32)
string(REGEX MATCHALL "\r\n" nLines ${fileData})
else()
string(REGEX MATCHALL "[\r\n]" nLines ${fileData})
endif(WIN32)
list(LENGTH nLines nLines)
set(${_nLinesVar} ${nLines} PARENT_SCOPE)
else()
set(${_nLinesVar} -1 PARENT_SCOPE)
endif()
Cheers!
Johny
_______________________________________________
Powered by www.kitware.com
Visit other Kitware open-source projects at
http://www.kitware.com/opensource/opensource.html
Please keep messages on-topic and check the CMake FAQ at:
http://www.cmake.org/Wiki/CMake_FAQ
Follow this link to subscribe/unsubscribe:
http://www.cmake.org/mailman/listinfo/cmake