in reply to Interesting Use for "state" Variables

The D language has a nice pragmatic variation on the foreach loop.

Written this way, c takes on each of the values in the array a in turn:

char[] a; ... foreach (char c; a) { ... }

Written this way, the same thing happens, but also i takes on the index of the value also:

char[] a; ... foreach (int i, char c; a)

I don't think there's any possibility of getting that into 5.12 (nor even Perl 6 at this late stage), but it one of those few features of other languages I miss when I'm writing Perl.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Interesting Use for "state" Variables
by massa (Hermit) on Mar 10, 2009 at 02:53 UTC
    perl6 already has the kv thingy:
    for @x.kv -> $index, $value { say $index, ' ', $value }
    (tested with rakudo, it works)
    []s, HTH, Massa (κς,πμ,πλ)
Re^2: Interesting Use for "state" Variables
by eyepopslikeamosquito (Archbishop) on Mar 10, 2009 at 15:44 UTC

    Python has enumerate for this. For example:

    for i, item in enumerate(array): do_something_with(item, i)
    The nearest thing I can find to that in Perl is the List::MoreUtils pairwise function, something like:
    my @idx = 0 .. $#array; pairwise { do_something_with($b, $a) } @idx, @array;
    or perhaps the CPAN Array::Each::Override module.

      You can achieve something similar without modules a couple of ways:

      @a = 'A'..'J'; for my $r ( map { k=> $_, v=> $a[ $_ ] }, 0 .. $#a ) { print "@{ $r }{ k, v }\n" } 0 A 1 B 2 C 3 D 4 E 5 F 6 G 7 H 8 I 9 J

      Or

      @a = 'A'..'J'; for my $r ( map [ $_, $a[ $_ ] ], 0 .. $#a ) { print "$r->[0]:$r->[1]\n" } 0:A 1:B 2:C 3:D 4:E 5:F 6:G 7:H 8:I 9:J

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.