Any explanation of what I am doing wrong and how to achieve what I need (retrieving the last item from the loop and assigning it to $app instead of iterating through the whole loop) would be appreciated.

I have weird errors in the logs and the page won't load. Here is what the error log says:

$data2 is a reference to a hash. The pop() function takes an array as an argument. Because $data2 references a hash, there is no concept of a "last" element to remove. So you're going to need to rethink what it is you're trying to do.

In your case, the loop was iterating over the array referenced by $data2->{record}. You can access the last element of that with pop, however:

my $app = pop @{$data2->{record}};

Email codedump link for Syntax errors while trying to change a foreach loop