in reply to Accessing array elements

If you look at code written by Perl experts then you'll probably notice that they very rarely use the C-style for loop like you're using here. Most people find the shell-style foreach loop far easier to deal with.

In this case, I think you want:

foreach my $i (0 .. ($#array/2) - 1) { ... }
--

See the Copyright notice on my home node.

Perl training courses

Replies are listed 'Best First'.
Re^2: Accessing array elements
by JavaFan (Canon) on Jun 18, 2009 at 15:02 UTC
    But the set of people who avoid using C-style for loop are typically the ones that avoid $# as well.

    I do use the C style for loop if I want the index, because, IMO, it's easier to avoid off-by-one errors than using foreach style. The latter means you either have to use '- 1', or remember to use '$#'.

    for (my $i = 0; $i < @array; $i++) {...}
    is standard idiom which translates easily between languages. Both
    foreach my $i (0 .. @array - 1) {...}
    and
    foreach my $i (0 .. $#array) {...}
    feel artificial, and Perl specific to me. And they both have their ugliness (either -1 or $#array).
Re^2: Accessing array elements
by AnomalousMonk (Archbishop) on Jun 18, 2009 at 16:40 UTC
    foreach my $i (0 .. ($#array/2) - 1) { ... }
    This produces an off-by-one error. Either
        ($#array/2)
    or the uglier
        (@array/2) - 1
    works as I understand the OPer requires.
    >perl -wMstrict -le "my @ra = qw(a A b B c C d D e E); for my $i (0 .. ($#ra/2) - 1) { print qq{$ra[ $i * 2 ] : $ra[ $i * 2 + 1 ]}; } " a : A b : B c : C d : D >perl -wMstrict -le "my @ra = qw(a A b B c C d D e E); for my $i (0 .. ($#ra/2)) { print qq{$ra[ $i * 2 ] : $ra[ $i * 2 + 1 ]}; } " a : A b : B c : C d : D e : E