Cyber Sentry
Application Development
System Architecture Design
Technical Due Diligence
Qmail Support and Consultancy
Scripting Help
Partners
Client Testimonials
Help Sections
Software Patents
Site Map
Contact us
Community
Home

Array assignments

Remember, that perl will evaluate a variable when it is called, and as such a viariable which is called at one time in the program can be changed and outputted diferently later.

 

The first assignment below explodes the @music variable so that it is equivalent to the second assignment.

 

@moremusic = ("organ", @music, "harp");

@moremusic = ("organ", "whistle", "flute", "harp");

 

This should suggest a way of adding elements to an array. A neater way of adding elements is to use the statement

 

push(@food, "eggs");

 

which pushes eggs onto the end of the array To push two or more items onto the array use one of the following forms:

 

push(@food, "eggs", "lard");

push(@food, ("eggs", "lard"));

push(@food, @morefood);

 

The push function returns the length of the new list.

 

To remove the last item from a list and return it use the pop function. From our original list the pop function returns eels and @food now has two elements:

 

$grub = pop(@food); # Now $grub = "eels"

 

It is also possible to assign an array to a scalar variable. As usual context is important. The line

 

$f = @food;

 

assigns the length of @food, but

 

$f = "@food";

 

turns the list into a string with a space between each element. This space can be replaced by any other string by changing the value of the special $" variable. This variable is just one of Perl's many special variables, most of which have odd names.

 

Arrays can also be used to make multiple assignments to scalar variables:

 

($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;

($a, $b) = @food; # $a and $b are the first two

# items of

($a, @somefood) = @food; # $a is the first item of @food

# @somefood is a list of the

# others.

(@somefood, $a) = @food; # @somefood is @food and

# $a is undefined.

 

The last assignment occurs because arrays are greedy, and @somefood will swallow up as much of @food as it can. Therefore that form is best avoided.

 

Finally, you may want to find the index of the last element of a list. To do this for the @food array use the expression

 

$#food

 

Displaying Arrays

Remember, the context in which you call a variable is important, co the following will give diferent results:

 

print @food; # By itself

print "@food"; # Embedded in double quotes

print ""; # In a scalar context

 



Qmail Help Section
Perl Tutorial
Linux Command Line Help
Top top Copyright Cyber Sentry Ltd  

Cyber Sentry -- Application Development Sitemap 1 2 3