Rename mass files with text from first line

I have a few hundred text files that are currently numbered files. I would like to rename each one with the text from the first line in the file. I would prefer this is perl script rather than a one liner as it wil be after many alterations to the file via an existing script. Any help would be greatly appreciated.

Try this:

for file in *
do
   # Avoid renaming diretories!
   if [ -f "$file" ]
   then
       newname=`head -1 $file`
       if [ -f "$newname" ]
       then
              echo "Cannot rename $file to $newname - file already exists"
       else
              mv "$file" "$newname"
       fi
   fi
done