keys %hash returns an array of keys.
sort returns an array sorted in ascii table order.
So you are getting a list (array) of keys, then sorting that list.
Then the foreach iterates over each element in our new list with each element assigned to '$key' until we run out of elements
$key will contain 'A', 'B', etc. so we can access our array values with $hash{$key}