my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)];
my ($last_arr_index, $next_arr_index);
Jeśli trzeba znać rzeczywisty indeks ostatniego elementu, na przykład trzeba pętli nad elementów tablicowych wiedząc indeksu, należy $#$
:
$last_arr_index = $#{ $arr_ref };
$last_arr_index = $#$arr_ref; # No need for {} for single identifier
Jeśli trzeba znać indeks elementu po ostatnim, (np. wypełnić kolejny wolny element bez push()
),
ALBO musisz znać ilość elementów w tablica (który jest taki sam numer) jak wyżej:
my $next_arr_index = scalar(@$arr_ref);
$last_arr_index = $next_arr_index - 1; # in case you ALSO need $last_arr_index
# You can also bypass $next_arr_index and use scalar,
# but that's less efficient than $#$ due to needing to do "-1"
$last_arr_index = @{ $arr_ref } - 1; # or just "@$arr_ref - 1"
# scalar() is not needed because "-" operator imposes scalar context
# but I personally find using "scalar" a bit more readable
# Like before, {} around expression is not needed for single identifier
Jeśli rzeczywiście potrzebujesz to dostęp do ostatni element w arrayref (np tylko powód, dla którego chcesz poznać indeks, to późniejsze użycie tego indeksu do dostępu do elementu), możesz po prostu użyć faktu, że indeks "-1" odnosi się do ostatniego elementu tablicy. Rekwizyty do posta Zaida dla pomysłu.
$arr_ref->[-1] = 11;
print "Last Value : $arr_ref->[-1] \n";
# BTW, this works for any negative offset, not just "-1".
Dzięki DVK. Właśnie o tym myślałem, kiedy zapisałem odpowiedź. – Zaid