Now lets have a little fun exploring what else you can do with lists. Just like with scalars, you can pass
variable data into lists as well as assigning it directly. In the next example, you'll see we do a simple addition, then put the result into a list.
#!/usr/local/bin/perl
$addedValue = 1 + 2;
print "$addedValue\n";
@myNumbers = (1, 2, $addedValue);
print @myNumbers;
This will output:
$ ./simpleProgram.pl
3
123$
In fact, you can even perform operations within the parenthesis when you assign the array. You should see the same output as the first program here:
#!/usr/local/bin/perl
$addedValue = 1 + 2;
print "$addedValue\n";
@myNumbers = (1, 1+1, $addedValue);
print @myNumbers;
Let's try something a little fancier and use one of Perls many built in functions. Using functions you can perform specialized operations on scalars and lists like moving and sorting the order. Take a look at the following program.
#!/usr/local/bin/perl
@myNumbers = (1, 2, 3);
print @myNumbers;
print "\n";
print reverse(@myNumbers);
print "\n";
The newlines are just there to make the output a bit more readable. You should see something like this:
$ ./simpleProgram.pl
123
321
$
Just by using the
reverse function, we were able to reverse the order of the scalars in the list. There are many more functions to explore in the core library, but for now just remember the following points:
- A list is the second of 3 basic data types in Perl.
- A list is an ordered set of virtual boxes that each holds a single piece of data.
- You can use operators to modify the data within your list, just like a scalar, and access it using the @arrayName you designate.
Next:
Beginning Perl Tutorial - Data Types: Hashes