Array can be defined as a collection of objects. In PERL, the array is a collection of scalar variables however it can also contains other arrays as well.
1. Defining an array with 0 elements
@names = ();
declares an empty array variable.
2. To declare an array with arbitrary set of elements
@names = ("vipul","atul","rahul");
3. Array can also be declared without any double quotes (") using the following notation
@names = qw(vipul atul rahul);
qw here refers to the quote word function and the values need to be separated by space delimiter.
4. Finding the array size.
Assigning the @names to a scalar variable $len will give the length of an array i.e. the number of elements in an array
my $len=@names;
assigns the size of the array to a variable by name $len. In this case the value of $len will be 3
Note: Please note what is the value of @array will be based in the context in which array variable is being used. For example, in the scalar context like this:
my $len = @array + 1;
the value of @array will be treated as the length of an array as assigning the array (set of values) to a scalar doesn’t make any sense However in the context below
print "Content of array is " . @array;
the @array will print the content of arrays rather than printing the length of an array.
Question: How to shuffle the content of arrays at random?
Answer: With perl 5.x versions the List::Util 'shuffle' subroutine can be used to shuffle the content of an array. This comes handy for the programs where the random values need to be feed
use List::Util 'shuffle';
@names = qw(chintul atul vips rahul kits mom dad);
@random_names = shuffle(@names);
print join " ", @random_names ;
Please note that every time we run the program the array gets shuffled and we get the different output while we execute the program.
C:\shuffle_array.pl
atul kits dad rahul mom vips chintul
C:\shuffle_array.pl
rahul atul mom dad chintul vips kits
C:\shuffle_array.pl
mom vips rahul chintul dad kits atul
Reference: For the beginners the best way to learn about arrays is to work with simple programs and search N number of articles available online. One excellent resource to learn can be the available perldocs. At the command prompt simple type the command below to learn more about the Arrays.
perldoc -q array
Saturday, April 3, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment