Perl dosn't require to provide number of size or elements while declaring a new array like other programming languages. For example java/c++ requires something as below
But for Perl, you can easily declare an array without specifying the size of the array. But It may require sometimes that you need to declare an array of size 20 having values are from 1 to 20 serially. You can declare the array first, and fillup the array using a loop easily. But what will be the proper Perl style? Here it is.
Now, another interesting thing. You need to declare an array with size 20, and all the values will be initialized by 5. Will you do a loop once again? Exactly not. Cause Perl have its own style again. Here is the example
Thats all for today. If anyone has better idea on initializing the Perl array, can share here. Thanks for reading the post.
int array[] = new int[10];
int a[10];
But for Perl, you can easily declare an array without specifying the size of the array. But It may require sometimes that you need to declare an array of size 20 having values are from 1 to 20 serially. You can declare the array first, and fillup the array using a loop easily. But what will be the proper Perl style? Here it is.
## declare the array of size 20,
## from index 0-19 values will be 1-20
my @arr = (1..20);
## print the array using function join()
print join("\n", @arr);
Now, another interesting thing. You need to declare an array with size 20, and all the values will be initialized by 5. Will you do a loop once again? Exactly not. Cause Perl have its own style again. Here is the example
## declare the array of size 20,
## all will initialize with 5
my @arr = ((5) x 20);
## print the array using function join()
print join("\n", @arr);
Thats all for today. If anyone has better idea on initializing the Perl array, can share here. Thanks for reading the post.
Comments
http://youvd.com
http://www.youtube.com/watch?v=cEoEBa8EUrE
my @arr = ( (0) x 128 );
my $size = 20;
my @array;
$array[$size-1] = undef;
my $length = scalar(@array); # 20
my $last_index = $#array; # 19