Page 1 of 1

Arrays (part 1) Rate Topic: -----

#1 jumptrooper  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 68
  • View blog
  • Posts: 234
  • Joined: 19-August 10

Posted 15 February 2011 - 12:51 PM

Lists and Arrays

As Mentioned in Sam's Teach Yourself Perl in 24Hours,
when you want to work with a bunch of things in Perl, you use list data. Perl provides 3 different ways to do this: lists, arrays, and hashes.

For this tutorial, we will just focus on lists and arrays (because they're very closely related)

Lists are very simple. Sometimes you will see them written as a set of parentheses encasing a group of scalars, separated by commas, like this: (2, 5, $a, "Joe").
Each scalar in the list is called a list element.
Lists can be arbitrarily large.

Lists on their own are not very useful (or at least I don't see how they are very useful). To make them more useful, you can store a list inside an array variable. Array variables, in Perl, are designated with the "@" symbol in front of the variable's name.
Thus, @myArray = (2, 5, $a, "Joe"); would be one way to store the list we created earlier in the variable @myArray so that we can referr to the elements of @myArray later on in our program.
Note that @myArray and $myArray are two different variables and can be used within the same program scope. @myArray is an array while $myArray is a scalar variable.

Here are some other ways to store list data into an array variable:
@myArray = (5, 'apple', $x, 3.14159);


This line stores the number 5, the string literal apple, the value stored in $x and the number Pi in the array @myArray.

@myArray = qw(5 apple $x 3.14159);

This line uses the qw() operator to treat each list element as though it were separated by commas and enclosed in single quotes, making it equivalent to @myArray = ('5', 'apple', '$x', '3.14159');. In this case each element would be treated as a string literal. This means '$x' is literally '$x' and not "the value stored in $x".

@myArray = qq(5 apple $x 3.14159);

This line does the same as the previous, except that each element is treated as though it were enclosed in double quotes, causing Perl to interpolate each element. As a result, each element is evaluated as a string, however, variables such as '$x' are interpolated to be "the value stored in $x".

@copy = @myArray;

Here, the values stored in myArray are copied over to @copy.

@clean = ();

Here, @clean is set have zero elements.

Ranges of values can also be assigned easily to an array.
@array = (1..10);

produces an array with elements 1 through 10 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
@array = (1..10, 20..30);

produces an array with elements 1 through 10 and 20 through 30 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29. 30)
@boys = qw(Greg Peter Bobby);
@girls = qw(Marcia, Jan Cindy);
@kids = (@boys, @girls);

The elements of @boys are stored in @kids and then the elemements of @girls are stored in @kids, making @kids contain the flattened list ('Greg', 'Peter', 'Bobby', 'Marcia', 'Jan', 'Cindy')
@family=(@kids, ('Mike', 'Carol'), 'Alice');

Here, the elements of the array @kids are stored in @family, then the list ('Mike', 'Carol') is stored in @family, and finally the string 'Alice' is stored in @family. The resulting array is: ('Greg', 'Peter', 'Bobby', 'Marcia', 'Jan', 'Cindy', 'Mike', 'Carol', 'Alice')

Here are some other interesting ways to do assignments with lists and arrays:
($a, $b, $c) = qw(apples oranges bananas);

This line is equivalent to $a = 'apples'; $b = 'oranges'; $c = 'bananas';

($a, @fruit, $c) = qw(peaches mangoes grapes cherries);

This one is illustrates something to be careful of. The result of this assignment is that $a contains 'peaches' and @fruit contains everything else, while $c is left undefined. What you should know is that assigning to an array is a "greedy" process, meaning that the array will slurp up everything that's left in a list. This means that (@array1, @array2) = qw(1 2 3 4 5); will result in @array1 containing all the elements and @array2 being undefined.

Here is another thing to be aware of:
($t, $u, $v) = qw(a b c d);

results in 'd' going unused and discarded.
Also...
($a, $b, $c, $d) = qw(x y z);

results in $d being undefined.
The lesson is that you need to pay attention to the number of elements on both sides of an assignment operation.

Now lets talk about how to get elements back out of an array!

If you just want to print the elements of an array you can just type:
print "@array";

and you will see something like (depending on what's in the array) : 1 2 3 4 5 6 printed to the screen.

Like most languages, single elements of an array can be retreived by specifying an index value, begining with 0.
Therefore, if @array = qw(1 2 3 4); then print $array[2]; would output "3" to the screen.

"Wait! What's that "$" doing there?"

I'm glad you asked!

When we use "$array[2]", we're referring to an individual scalar value inside the array, not the array itself as a whole.
You might then wonder why "print @array[2];" produces the same result and why I'd tell you that you access elements of an array using a "$" instead of a "@".
Here's what's happening. Suddenly we're dealing with "Context". When you use "$" you're telling Perl your giving it a scalar value and when you use "@" you're telling Perl you're giving it a list value. Perl will do different things depending on what kind of context it is operating in. There are two contexts in which Perl operates (correct me if I'm wrong) Scalar Context and List Context.

Scalar context is when Perl expects scalar data while List context is when Perl expects list data - helpful, I know. Let me elaborate:
Scalar variables hold single pieces of information (a number, a string, a character, etc). Lists are, essentially, collections of scalar variables. When performing certain operations, Perl will expect one kind of data or the other and will interpret whatever you provide in the context of what it was expecting.

Long story short: @array[2] is telling Perl that you're giving it a single element "slice" (subarray/sublist) of @array begining at index 2.
Therefore:
@array = qw(1 2 3 4);
$x = @array[2];
is the same as
$x = ('3');


while
@array = qw(1 2 3 4);
$x = @array[2,3,0];
is the same as 
$x = ('3', '4', '1');

which, by the way, would result in $x ending up with the value '1' stored in it because storing a list in a scalar results in only the last list element being stored - it's as if you did:
$x = '3';
$x = '4';
$x = '1';


Moral of the story:
Use "$array_name[index_number]" to access a single array element.

Finding the number of elements in an array

$numElements = @myArray;

This stores the number of elements of @myArray in $numElements.
Be aware that arrays can be arbitrarily long and their size is only limited by the systems memory.

Finding the last index of an array

Use "$#myArray" to get the last accessible index of an array
So,
@myArray = qw(1 2 3);
$x = $#myArray;
print $x;


would print "2" becuause "2" is the last index in which a value is stored.

Quirky things about arrays

Here's something fun: an array index does not have to exist before you can reference it! "YAY! Wait! Huh?"
So, for example:
@myNewlyCreatedArrayWithNothingInIt = ();

$myNewlyCreatedArrayWithNothingInIt[5] = "random string";

print @myNewlyCreatedArrayWithNothingInIt;


would print
random string

and
@myNewlyCreatedArrayWithNothingInIt = ();

$myNewlyCreatedArrayWithNothingInIt[5] = "random string";
$myNewlyCreatedArrayWithNothingInIt[1000] = 32;

print @myNewlyCreatedArrayWithNothingInIt;
print "\n";
print $#myNewlyCreatedArrayWithNothingInIt;
print "\n";


would print
random string32
1000


and
@myNewlyCreatedArrayWithNothingInIt = ();

$myNewlyCreatedArrayWithNothingInIt[5] = "random string";
$myNewlyCreatedArrayWithNothingInIt[1000] = 32;

print "@myNewlyCreatedArrayWithNothingInIt  \n";

print "$#myNewlyCreatedArrayWithNothingInIt \n";


would print
[spaces]   random string              [...lots of spaces....]  32
1000



This is another example of Perl operating differently under different contexts. In the first example Perl was told to print the elements of the array and since "random string" was the only element, that's all it printed. In the second example, "32" was added to the array at index 1000. Since there were two elements in the array it printed both elements (with no spaces between elements, which is how Perl likes to do this sort of thing). It also printed the last index value, which of course, is 1000. The third example does something different because the context changed. Notice the double quotes around @myNewlyCreatedArrayWithNothingInIt. The double quotes causes Perl to interpolate the variables inside of it. In the case of arrays/lists this means that it will print every element with a space in between it ('cuz that's more perrrrty). Because our array only has two elements at index 5 and index 1000, Perl printed what amounts to
"'' '' '' '' '' 'random string' '' '' .....[lots of '' '' ] ...... '' 32 \n"

And I think this is where I will leave off for now. There are still several things to go over, such as adding and removing elements, resizing arrays, spliting strings into arrays, joining arrays into single strings and all sorts of other fun features.

Please ask questions if things are not clear - don't worry if it's a year later, I don't mind :)


Is This A Good Question/Topic? 1
  • +

Page 1 of 1