Tuesday, March 10, 2009

Perl : Initialize an array.

Share at Facebook

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

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.


Anonymous said...

view freeze youtube whats up !!!!!!!! change now for youvd.com

joe-lo said...

can you please fix this view count


Anonymous said...

Thanks! it helped me initialize my array full of zeros
my @arr = ( (0) x 128 );

Marcos Ramos said...

If you want to initialize an array with 20 positions in Perl, the best and fastest way is:

my $size = 20;
my @array;
$array[$size-1] = undef;

my $length = scalar(@array); # 20
my $last_index = $#array; # 19