in reply to my array is almost a hash, but keys are not unique.

50 lines? What language? A slightly more efficient option:

my $in = [ one => 1, two => 2, two => '2.003' ]; my $out = {}; for(my $i=0; $i<$#$in; $i+=2) { push @{$out->{$in->[$i]}}, $in->[$i+1]; }

or for a game of golf

my $i=0; push(@{$out->{$in->[$i++]}},$in->[$i++]) while $i<$#$in;

Best, beth

Replies are listed 'Best First'.
Re^2: my array is almost a hash, but keys are not unique.
by Boldra (Curate) on Apr 03, 2009 at 08:40 UTC
    Well, I don't want to embarrass him too much, but his approach was to step through the array, look at each element and guess whether it was meant to be a key or a value, then use a '$last_key' variable to put the value into a new hash. There's also quite a bit of warning code in his routine, leftover from debugging.


    - Boldra
Re^2: my array is almost a hash, but keys are not unique.
by GrandFather (Saint) on Apr 06, 2009 at 02:37 UTC

    The golfed version may not 'Do The Right Thing'™ due to the uncertainty of the order of evaluation of the two increments, and even if it works today, it may not work tomorrow with a different version of Perl.


    True laziness is hard work

      Which is exactly why I offered it as a golfed version only - but I probably should have mentioned that lest someone use the golfed version in production code. Hopefully you've saved someone a world of trouble.

      Being an old C programmer, I was taught never to trust the order of evaluation of parameters (right to left, left to right or something in between). But it does seem to work consistently on my version of Perl (5.8.8) - raising the question: does Perl have a defined order of evaluation for parameters or is it like "other languages" and leaves order to the optimizer and compiler implementation? I looked for a citation either way this AM and had no luck.

      Best, beth

        In golf you still have to get the ball in the hole generate the correct result. Bugs in golfed Perl are still bugs. ;)

        In the second paragraph of the Auto increment and Auto decrement section of perlop it says:

        Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behaviour.

        True laziness is hard work