Array size in Perl -
i trying run code , getting output as:
#!/usr/bin/perl @array = (1,2,3); $array[50] = 4; $size = @array; $max_index = $#array; print "size: $size\n"; print "max index: $max_index\n";
output:
size: 51 max index: 50
what explanation this?
in perl, array data structure representing list. list has elements. keys list called indexes. first index 0 (0
).
you have started array these indexes , valus:
index value 0 1 1 2 2 3
if set 50th index value, other indexes in between filled undef
, undefined value.
you have correctly identified $#array
max index, or highest or last index. if force array scalar context, give number of elements, or size. you've got well. , will, Сухой27 said in comment, last index minus one.
you can illustrate behaviour if dump out array.
use strict; use warnings; use data::printer; @array = (1,2,3); $array[10] = 4; p @array;
it output following. again can see index starts @ 0
, , each number between 0
, highest index there. number of elements 1 less last element's index.
[ [0] 1, [1] 2, [2] 3, [3] undef, [4] undef, [5] undef, [6] undef, [7] undef, [8] undef, [9] undef, [10] 4 ]
this might confusing if come php background, array can indexes or associative , still called array. in perl called hash , not ordered.
i suggest read on how perl data structures work in perldata.
Comments
Post a Comment