@array = ('x', 'x', 'y', 'z', 'z', 'z'); my %items; for my $i (0 .. $#array) { $items{$array[$i]} ||= [ $i, $i ]; # only assigns for the first occurrence $items{$array[$i]}[1] = $i; # replaces for every new occurrence } use Data::Dumper; print Dumper \%items; #### $VAR1 = { 'x' => [ 0, 1 ], 'y' => [ 2, 2 ], 'z' => [ 3, 5 ] };