FAQ 4.40 What is the difference between $array[1] and @array[1]?

P

PerlFAQ Server

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

4.40: What is the difference between $array[1] and @array[1]?

(contributed by brian d foy)

The difference is the sigil, that special character in front of the
array name. The "$" sigil means "exactly one item", while the "@" sigil
means "zero or more items". The "$" gets you a single scalar, while the
"@" gets you a list.

The confusion arises because people incorrectly assume that the sigil
denotes the variable type.

The $array[1] is a single-element access to the array. It's going to
return the item in index 1 (or undef if there is no item there). If you
intend to get exactly one element from the array, this is the form you
should use.

The @array[1] is an array slice, although it has only one index. You can
pull out multiple elements simultaneously by specifying additional
indices as a list, like @array[1,4,3,0].

Using a slice on the lefthand side of the assignment supplies list
context to the righthand side. This can lead to unexpected results. For
instance, if you want to read a single line from a filehandle, assigning
to a scalar value is fine:

$array[1] = <STDIN>;

However, in list context, the line input operator returns all of the
lines as a list. The first line goes into @array[1] and the rest of the
lines mysteriously disappear:

@array[1] = <STDIN>; # most likely not what you want

Either the "use warnings" pragma or the -w flag will warn you when you
use an array slice with a single index.



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top