in reply to Loops in Perl

G'day carlriz,

Let's say @sorted_positions has five elements (1, 3, 5, 7, 9). (So, $#sorted_positions will be 4.)

The code you posted:

@ranks[@sorted_positions] = (0 .. $#sorted_positions);

will be evaluated like this:

@ranks[1, 3, 5, 7, 9] = (0, 1, 2, 3, 4);

The element $ranks[1] will be set to 0, the element $ranks[3] will be set to 1 and so on.

Here's a short piece of code demonstrating this.

#!/usr/bin/env perl -l use strict; use warnings; my @ranks = qw{a b c d e f g h i j}; my @sorted_positions = (1, 3, 5, 7, 9); print "@ranks"; @ranks[@sorted_positions] = (0 .. $#sorted_positions); print "@ranks";

Output:

a b c d e f g h i j a 0 c 1 e 2 g 3 i 4

The elements with indices 0, 2, 4, 6 and 8 are unchanged. The remaining elements (with indices 1, 3, 5, 7 and 9) are set to the values 0, 1, 2, 3 and 4 respectively.

-- Ken

Replies are listed 'Best First'.
Re^2: Loops in Perl
by carlriz (Beadle) on Mar 12, 2014 at 00:48 UTC

    Awesome example. Thanks!