Perl6 RFC Librarian writes:
>     foreach $item (@array) {
>         print $item, " is at index ", $#, "\n";
>     }
> 
> 
> The variable C<$#> currently holds the output format for printed
> numbers.

This would slow down all foreach loops, even those that didn't need to
know $#.  It's a similar problem to $` and friends, where Perl can't
know when you're going to use them so has to save data from all
matches if it sees you use the variables anywhere in your program.

Better would be to think of scoping constructs that make this and
other problems easier to solve.

  foreach $item (@array) {
    my $n : static = 0; # initialized each time foreach loop starts
    print "$item is at index $n\n";
    $n++;
  }

This replaces the currently cumbersome:

  {
    my $n = 0;
    foreach $item (@array) {
      print "$item is at index $n\n";
      $n++;
    }
  }

The RFC only shows foreach()ing across @array.  The for() loop isn't
bad for simple arrays.  The real kicker is that you can't use a for()
loop if you're foreach()ing across a list unless you first store that
list in an array variable:

  # rewrite *this* as a for loop without a temporary variable
  foreach $item (split //, $string) 

As well as static, you could even have a :counter attribute that
incremented the variable each time the my declaration was reached.

  my $n : counter = 0;  # initialized to 0 first time
                        # incremented by 1 subsequent times

This might be too specialized, though.

I'm in favour of trying to solve general problems rather than specific
ones.

Nat

Reply via email to