Place first non-blank paragraph of text file into a variable?

I’m working on a script that processes and converts word-processing files into a different format. When the script opens an old file from a DOS PC, and the file has no file type or creator code, I read the first paragraph of the file into a variable and display that variable to the user. This is the code I use to extract the first paragraph of the file:

set checkItem to choose file
my readfile(checkItem)

on readFile(checkItem)
	set openCheckItem to (open for access checkItem)
	set fileText to (read openCheckItem for (get eof openCheckItem))
	close access openCheckItem
	set paragraphList to every paragraph of fileText
	set firstPara to first item in paragraphList
end readFile

In some files, the first few paragraphs are blank, and I want to display the first non-blank paragraph. I can’t figure out how to change this code so that it tests the first ten paragraphs, and displays the first non-blank one.

Could anyone kindly help me out with this? Thank you for any advice.

Hi,

try this, the open for access construct is probably not needed.
The handler returns an empty string, if the file is empty or there is no non-blank paragraph within the first ten paragraphs.


set checkItem to choose file
set firstNonBlankParagraph to readfile(checkItem)

on readfile(checkItem)
	try -- in case the whole file is empty
		set paragraphList to paragraphs of (read checkItem)
		repeat with i from 1 to 10
			set currentParagraph to item i of paragraphList
			if currentParagraph is not "" then return currentParagraph
		end repeat
	end try
	return ""
end readfile


That is both elegant and efficient - and it works perfectly. Thank you, Stafan!