Re: array question (newbie)
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 31 Aug 2005 07:50:04 -0700
Jerry Cloe wrote:
> Having an array:
>
> @mylist=("apples", "oranges", "bananas");
>
> And refering to a particular element, which syntax is correct? (or are both
> correct)?
>
> print "Item 2 is $mylist[1]\n";
> or
> print "Item 2 is @mylist[1]\n";
>
> Both seem to work, and looking at other code, I see it done both ways.
That "other" code is almost assuredly wrong. Please do see the
responses by other posters. In the meantime, however, some more
information:
both $foo[1] and @foo[1] will most likely Do What You Want - When
you're READING them only. If you are writing to the two values, you
are imposing two different contexts on whatever you're evaluating. The
FAQ that others have referred you to gives as an example reading the
output of an external program through back-ticks. Here's a possibly
more simple-to-understand example:
my @sizes;
my (@foo, @bar);
@foo = (4..12);
@bar = qw/a b c d e f g h i j/;
$sizes[0] = @foo; # correct, sets $size[0] to size of @foo, which is 9
@sizes[1] = @bar; # OOPS! sets $size[1] to the *first element* of
foo,
# which is 'a';
The reason for this is that $size[0] is a scalar value, and so scalar
context is imposed on the array @foo. An array in scalar context
returns its size.
@size[1], on the other hand, is a list containing a single value.
Assigning to a list imposes list context. This line is equivalent to
having done:
my ($size) = @bar;
rather than
my $size = @bar;
When you assign one list to another, the values are copied over
directly. The first value on the right gets assigned to the first
variable on the left, the second on the right to the second on the
left, etc.
The reason Perl warns you when you use @size[1] even in a read (when it
would actually probably not hurt your code) is that getting into the
habbit of writing @size[1] when you mean $size[1] will come back to
bite you, when you attempt to use it in a write, as I did above.
I hope you find this explanation helpful...
Paul Lalli
.
- References:
- array question (newbie)
- From: Jerry Cloe
- array question (newbie)
- Prev by Date: Re: Perl match problem
- Next by Date: DOM from XML without C libs?
- Previous by thread: Re: array question (newbie)
- Next by thread: Is it possible to resize or crop JPG image with Perl?
- Index(es):
Relevant Pages
|