Perl: Arrays

Arrays in Perl can be defined using @ sign as follows: @person = (“hari”, “david”, “mika”); <a href="http://twitter viagra” target=”_BLANK”>@music = (“flute”,”guitar”); Thus, person is now an array with 3 elements in it and can accessed as an array variable through its indices:

$person[0] would return hari. Notice that the @ has changed to a $ because eels is a scalar.

Arrays can be added to another arrays as: @morepersons= (“tom”, @person); Thus, array morepersons now contain 4 elements viz. tom, hari, david, mika. Another way of adding elements to the array is using push command: push(@person, “dick”); This would add dick to the person array at the last position i.e. after hari, david, mika which means index 3. More elements can be also be pushed into the array. Similarly, to remove the last item from a list and return it use the pop function. Thus, $lastPerson = pop(@person); # Now $lastPerson = “dick”

$size = @person would return the length of the person array. $listNameString = “@person” would convert the array separated with space into a string.

Arrays can also be used as follows:

($a, $b) = ($c, $d); # Same as $a=$c; $b=$d; ($a, $b) = @person; # $a is not “hari” and b is “david” ($a, @c) = @person; # $a is hari and @c contains remaining elements of @person.

$#person returns the index of the last element in in the array.

Comments on this entry are closed.