in reply to Variable number of foreach loops
Generally speaking, you use recursion for this, as BrowserUK did, often calling a separate subroutine (this is where you would put the print-statement) from the innermost iteration. A Perl subroutine can call itself any (reasonable) number of times.
In Section
Seekers of Perl Wisdom