understand and prevent 'Out of memory!' during sub recursionby Discipulus (Monsignor)
|on Nov 09, 2017 at 09:53 UTC||Need Help??|
Discipulus has asked for the
wisdom of the Perl Monks concerning the following question:
Hello monks and nuns!
This is more an itch than a problem: yesterday in CB came out a little simple quiz reported by 1nickt (who obviously knows many different solutions to the quiz). The problem sounded like: write a sub that receives arrays of strings and print them interleaved. I added the constraint that print order had to be not just mixed but the first element of each array, then the second etc..
obviously there are many, simple, ways to accomplish this with or without core modules. First thing that i supposed was to spot the max length of received arrays and build a loop (and this approach works ok).
But and here the itch, after a while i started mumbling about shift to death arrays skipping the max length computing and I ended with:
Which unfortunately, while printing the correct result, bring to an undesired Out of memory!
Now I understand that it goes out of memory because nothing stops the recursion, so i tried to break it but with no luck: inserting in the top of the sub exit unless $_ just prints first elements of each array and exits, &inter if $_ at the end does the same.
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.