Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re(2): What is the difference between a list and an array?

by dmmiller2k (Chaplain)
on Dec 11, 2001 at 23:51 UTC ( #131026=note: print w/ replies, xml ) Need Help??


in reply to Re: What is the difference between a list and an array?
in thread What is the difference between a list and an array?

Just to add my voice to this cacophany ...

If I recall my own confusion on this point correctly, and the explanation that helped me finally turn the corner (toward understanding), a "list" may be described as a context, or a way of interpreting "thingys" (or variables), rather than as a thingy in its own right, whereas an array is one of three types of containers (thingys) your program may use to hold other thingys (information).

For example, an array, <CODE<>@a</CODE>, containing the three values, 'a', 'b' and 'c' (or @a = ('a', 'b', 'c')); in scalar context (in other words when the context requires a single value), it will evaluate as 3 (its number of elements). An example of this is a simple assignment to a scalar:

$x = @a;  # will contain 3

On the other hand, in list context (or, when the context permits multiple scalar values), the array will be flattened into a series of values of its elements, as in the classic case, when it is passed as a parameter to a (non-prototyped1) sub:

my_sub( @a ); # ... sub my_sub { # here the localized @_ variable contains references to # the list of values passed as paramters, for my $i (0 .. $#_) { print "param $i = $_[$i]\n"; } } # OUTPUT # param 0 = a # param 1 = b # param 2 = c

(Hashes may also be similarly flattened into lists, where the key/value pairs are guaranteed to remain adjacent and in 'key', 'value' order, but the ordering of the pairs is not necessarily deterministic.)

If array thingys and hash thingys and scalars are all intermingled in a given list context, they are all flattened into a single list of all the individual elements:

@a = ( 'I', 'am' ); %h = ( 'perl' => 'hacker' ); $x = 'just'; my_sub( @a, $x, 'another', %h ); # OUTPUT: # param 0 = I # param 1 = am # param 2 = just # param 3 = another # param 4 = perl # param 5 = hacker

1 Prototypes can alter this behavior, but that's a whole 'nother conversation.

dmm

You can give a man a fish and feed him for a day ...
Or, you can
teach him to fish and feed him for a lifetime


Comment on Re(2): What is the difference between a list and an array?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://131026]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-12-28 18:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (182 votes), past polls