develooper Front page | perl.perl6.language.flow | Postings from August 2000

RFC 120 (v1) Implicit counter in C<for> statements, possibly C<$#>.

Thread Next
From:
Perl6 RFC Librarian
Date:
August 16, 2000 13:25
Subject:
RFC 120 (v1) Implicit counter in C<for> statements, possibly C<$#>.
Message ID:
20000816202521.9108.qmail@tmtowtdi.perl.org
This and other RFCs are available on the web at
  http://dev.perl.org/rfc/

=head1 TITLE

Implicit counter in C<for> statements, possibly C<$#>.

=head1 VERSION

  Maintainer: John McNamara <jmcnamara@cpan.org>
  Date: 16 Aug 2000
  Version: 1
  Mailing List: perl6-language-flow@perl.org
  Number: 120

=head1 ABSTRACT

The syntax of Perl style C<for> statements could be simplified by the introduction of an implicit counter variable. The deprecated variable C<$#> could be used for this purpose due to its mnemonic association with C<$#array>.

=head1 DESCRIPTION

The following discussion make no differentiation between the C<for> and C<foreach> statements.

The use of the C<foreach> statement or the C<for> statement in conjunction with the range operator, C<..>, are generally seen as good idiomatic Perl:

    @array = qw(sun moon stars rain);
    
    foreach $item (@array) {
        print $item, "\n";
    }

as opposed to the "endearing attachment to C" style:

    for ($i = 0; $i <= $#array; $i++) {
        print $array[$i], "\n";
    }

However, the latter format is often more convenient if you need to keep track of the array index as well as iterating over the array:

    for ($i = 0; $i <= $#array; $i++) {
        print $array[$i], " is at index ", $i, "\n";
    }

is more succinct than:

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

The addition of an implicit counter variable in C<for> statements would lead to a more elegant syntax. It is proposed that the deprecated variable C<$#> should be used for this purpose due to its mnemonic association with C<$#array>. For example:

    foreach $item (@array) {
        print $item, " is at index ", $#, "\n";
    }


The variable C<$#> currently holds the output format for printed numbers. 


=head1 IMPLEMENTATION

Not sure. However, consideration would have to be given to nested C<for> statements and how the variable would be affected by C<local>.

=head1 REFERENCES

perldoc perlvar

Alex Rhomberg proposed an implicit counter variable on clpm: 
http://x53.deja.com/getdoc.xp?AN=557218804&fmt=text and 
http://x52.deja.com/threadmsg_ct.xp?AN=580369190.1&fmt=text 

Craig Berry suggested C<$#>: 
http://x52.deja.com/threadmsg_ct.xp?AN=580403316.1&fmt=text


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About