http://www.perlmonks.org?node_id=1222946


in reply to goto HACK

use strict; use warnings; use Data::Dumper; my @times = qw(1000 1000 1000 1010 1010 1010); my $hash = {}; for my $time (@times) { $time++ while exists $hash->{$time}; $hash->{$time}->{one} = 1; $hash->{$time}->{two} = 2; } print Dumper $hash;
Note that $time++ modifies the element of @times, since 'for' makes $time an alias of each element. If that's undesirable, copy $time to another var at the top of the loop, and use that instead.

Dave.

Replies are listed 'Best First'.
Re^2: goto HACK
by Anonymous Monk on Sep 25, 2018 at 09:24 UTC
    Note that $time++ modifies the element of @times, since 'for' makes $time an alias of each element.

    That's kinda creepy! I assumed declaring the var was making a copy of the element that wouldn't change the array. I can't believe I never noticed that... and the same with hash values, but not keys?

      Yes, the keys function returns temporary copies of the keys while values returns the actual values. So
      $_++ for @a; # modifies each element of @a $_++ for values %hash; # modifies every value of %hash $_++ for keys %hash; # doesn't do anything useful

      Dave.