Create a sub and call it in the foreach passing a (\%val,$_) each time around. in the sub, create a format with a name
and localize $~ (current format) like this
local $~ = 'SOME_FORMAT_NAME';
then just call write like this:
write();
return the total of price * quantity as a return value to the caller in the foreach loop and it to $total;
for the end print, just define the STDOUT format for printing the total after the last call to write immediately
outside the foreach (write automatically calls STDOUT).