Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between lists and arrays?

Tags:

arrays

list

perl

On this page, it shows how to initialize an array, and if you scroll down a bit, under the section called "The Lists" it "explains" what lists are and how they're different from arrays.

Except it uses an example that's just exactly the same as declaring an array, and doesn't explain it whatsoever.

What is the difference?

like image 589
temporary_user_name Avatar asked Dec 22 '12 09:12

temporary_user_name


People also ask

What is the difference between lists and arrays in Java?

List interface is used to create a list of elements(objects) that are associated with their index numbers. ArrayList class is used to create a dynamic array that contains objects. List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index.

What is the difference between array and list in C?

An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection.


1 Answers

Take a look at perldoc -q "list and an array". The biggest difference is that an array is a variable, but all of Perl's data types (scalar, array and hash) can provide a list, which is simply an ordered set of scalars.

Consider this code

use strict;
use warnings;

my $scalar = 'text';
my @array = (1, 2, 3);
my %hash = (key1 => 'val1', key2 => 'val2');

test();
test($scalar);
test(@array);
test(%hash);

sub test { printf "( %s )\n", join ', ', @_ }

which outputs this

(  )
( text )
( 1, 2, 3 )
( key2, val2, key1, val1 )

A Perl subroutine takes a list as its parameters. In the first case the list is empty; in the second it has a single element ( $scalar); in the third the list is the same size as @array and contains ( $array[0], $array[1], $array[2], ...), and in the last it is twice as bug as the number of elements in %hash, and contains ( 'key1', $hash{key1}, 'key2', $hash{key2}, ...).

Clearly that list can be provided in several ways, including a mix of scalar variables, scalar constants, and the result of subroutine calls, such as

test($scalar, $array[1], $hash{key2}, 99, {aa => 1, bb => 2}, \*STDOUT, test2())

and I hope it is clear that such a list is very different from an array.

Would it help to think of arrays as list variables? There is rarely a problem distinguishing between scalar literals and scalar variables. For instance:

my $str = 'string';
my $num = 99;

it is clear that 'string' and 99 are literals while $str and $num are variables. And the distinction is the same here:

my @numbers = (1, 2, 3, 4);
my @strings = qw/ aa bb cc dd /;

where (1, 2, 3, 4) and qw/ aa bb cc dd / are list literals, while @numbers and @strings are variables.

like image 179
Borodin Avatar answered Oct 18 '22 14:10

Borodin