Wild guess in the absence of information: the variable last contains spaces or some "poison" character (those that are significant to cmd).
Cure: set the target file to "%a%" not %a%. The enclosing quotes ensures batch interprets Space as an ordinary character, not a separator.
To assign a string to a variable, try using set "string=variable text" - the enclosing quotes ensure that any trailing spaces on the line are not included in the value assigned.
Note also that any spaces on either side of the = in a string-set statement will be included - either in the variablename or the string assigned.
Note also that your design appears to have a problem - what happens where there is more than one "lastname" in your list - John Doe and Jane Doe?