Your code breaches a topic in Perl that can be very confusing and Perl doesn't help by having a single syntactic solution. I would investigate a book like Intermediate Perl which dedicates several chapters to this topic.