To start with, just one (possibly silly) question: are you sure that the data structure you obtain with the "correct but slow" code is really what you want? I am asking that because the data structure you get with that does not seem terribly useful (at least in the limited context). A simple hash would appear to be more useful, and, in that case, the first attempt (which you qualify as wrong) seems OK.
Now, assuming that you really want a hash of arrays such as the one you build in your second code snippet, if anything is slow, it is probably not so much the foreach construct, which is pretty fast, but the fact that you are shifting the @values each time, meaning that Perl has to recalculate the @values array at each iteration.
The map version proposed by choroba is likely to be faster not so much because map is faster than foreach (most benchmarks that I have done show that the difference between the two constructs is usually quite small and foreach is quite often slightly faster, at least when they allow similar syntax constructs), but because it does not shift the @values array each time.
I did not do benchmarks and I may turn out to be wrong in that specific case, but I just wanted to call your attention on that for your consideration if you are going to benchmark various solutions.
Update: I was interrupted while writing the above and had to do something else. When I started to write this, there was only one answer (choroba's), I would probably not have written the above if I had seen all the other useful answers that came in between, since it turns out I am probably not saying very much new.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
Outside of code tags, you may need to use entities for some characters:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||