in reply to Running two loops

Unless I'm missing something, it sounds like you want to ignore data on certain lines. You don't need two loops and the convoluted structure for that, you just need some control modifiers.
while ($inline = <INPUT>) { @mag = split(/\s+/, $inline); next unless $mag[12] >= 12 && $mag[12] <= 20; #the rest of your code here, using @mag instead of @firstline; }
It looks like right now, you're trying to make two passes over your data, the first to decide what to deal with, the second to actually deal with it. It's usually much easier to just skip the data you don't need in a single pass.