in reply to remove both leading and trailing spaces
Given that $val holds the text as you describe in your code, I'd be using the following:
$val =~ s/ //g;
This will remove all "blanks" from the string and replace them with "nothing", thus removing all blanks from the string, in one swift stroke.
The "g" is important! Without it, it will only remove one blank from the string.