| [reply] [d/l] |
$[ = 10;
my @arr = ('a', 'b');
use Data::Dumper;
warn Dumper [ $#arr, scalar @arr ];
__END__
$VAR1 = [
'11',
2
];
Actually I think it would be better if this tool will suggest not to change $[ in the first place. | [reply] [d/l] [select] |
for my $i (0..$#array) {
...
}
No. The proper answer is not to avoid $#array, it's to avoid $[.
$[ has long been discouraged, it is deprecated in 5.12, and it will be removed for 5.14.
| [reply] [d/l] [select] |
$array[ 5 ]
Isn't that DWIM?
Why does @array in scalar context evaluate to the number of elements? Why not just use $#array + 1 and have an array in scalar context return the first element, or the sum of all the elements, or the total length of all the elements?
| [reply] [d/l] [select] |
[ I don't see any relation between your post and mine or any other post in this thread, so it's rather odd that you posted it here. Seekers of Perl Wisdom would have been a better place. Meditations would also have worked if you gave your opinion on the answers to these questions. ]
If we want the fifth element of an array why don't we say $array[ 5 ]? Isn't that DWIM?
For some, yes. For some, no. It depends on whether you think of array indexes as offsets or as positions. Beginners think in terms of positions, but there are many reasons to use offsets.
Why does @array in scalar context evaluate to the number of elements?
Because it's very convenient for it to do so.
Why not just use $#array + 1 and have an array in scalar context return the first element
It's much more common to want to know the number of elements in an array than to get its first element. Besides, it's already super easy to get the first element of the array ($array[0]).
or the sum of all the elements, or the total length of all the elements?
Aside that it would be rather arbitrary to choose between the two, these are very rarely needed operations that can easily be achieved by other means, such as
sum(@array)
and
length(join '', @array)
-or-
sum(map length, @array)
| [reply] [d/l] [select] |