in reply to Grabbing slices
which produces:@array = ('x', 'x', 'y', 'z', 'z', 'z'); my %items; for my $i (0 .. $#array) { $items{$array[$i]} ||= [ $i, $i ]; # only assigns for the first o +ccurrence $items{$array[$i]}[1] = $i; # replaces for every new occur +rence } use Data::Dumper; print Dumper \%items;
So it fills a hash of items, with an array with 2 entries for each: the first occurrence with index 0, and the last, index 1.$VAR1 = { 'x' => [ 0, 1 ], 'y' => [ 2, 2 ], 'z' => [ 3, 5 ] };
The tricks it uses to achieve this, is using ||=, which only assigns at the first occurrence, provided that what it assigns is always true; and = which always replaces what was there already, in the end leaving it in the state of the last assignment.
In case you have multiple ranges for the same item, it may or may not do what you want.
|
|---|