SPUG: basic array question

Can Subaykan cansubaykan at hotmail.com
Wed May 11 10:38:58 PDT 2005

Here are some examples of list context in action. Pay attention especially 
to the difference between the third and fourth examples, as that is a subtle 
but crucial difference.

# scalar = list literal, assigns last in list to scalar variable
$this = (2,3,4,5,6); # $this is 6

# array = list literal, assigns list to array variable
@nums = (2,3,4,5,6);

# scalar = array, assigns number of elements in array to scalar variable
$this = @nums; # $this is 5

# scalar in list context = array (or list), assigns first in list to scalar 
($this) = @nums; # $this is 2

# literal list = list, assigns each element and discards leftovers
($this, $that, $other) = ('a', 'b', 'c', 'd'); # $this = a, $that = b, 
$other = c

----Original Message Follows----
From: "Mathew D. Watson" <matw at eclipse-optics.com>
To: spug <spug-list at pm.org>
Subject: SPUG: basic array question
Date: Tue, 10 May 2005 14:40:31 -0700

I'm studying some perl fundamentals, and I'm cooking up examples
convince myself that I understand (or don't) what perl is doing. Here's
an "I don't" that I'm hoping you folks can explain.

#!/usr/bin/perl -w			# line 1
@a = (@x = (1, 2, 3), $y = 'a', 9);	# line 2
$a = (@x = (1, 2, 3), $y = 'a', 9);	# line 3
$b = @a;				# line 4

Please correct me if I write something wrong.

@a on line 2 has the value (1, 2, 3, 'a', 9), which makes sense. The
right hand side is evaluated in a list context because the variable on
the left hand side is an array.

$a on line 3 has the value 9, which is the last element of the array on
the rhs. What is the rule at work here? Is the rhs considered an array?
I'm not sure what context the rhs is evaluated in.

$b on line 4 has the value 5, the number of elements in @a, which is
what I thought might happen with $a on line 2. @a is evaluated in a
scalar context because the lhs is a scalar. Why aren't $a and $b the same?


Seattle Perl Users Group Mailing List
      POST TO: spug-list at pm.org
SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
     MEETINGS: 3rd Tuesdays, Location: Amazon.com Pac-Med
     WEB PAGE: http://seattleperl.org/

More information about the spug-list mailing list