Perl FAQ 5.1: What is the difference between $array[1] and @array[1]?

Perl FAQ 5.1

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

Always make sure to use a $ for single values and @ for multiple ones. Thus element 2 of the @foo array is accessed as $foo[1], not @foo[1], which is a list of length one (not a scalar), and is a fairly common novice mistake. Sometimes you can get by with @foo[1], but it's not really doing what you think it's doing for the reason you think it's doing it, which means one of these days, you'll shoot yourself in the foot; ponder for a moment what these will really do:

    @foo[0] = `cmd args`;
    @foo[1] = <FILE>
Just always say $foo[1] and you'll be happier.

This may seem confusing, but try to think of it this way: you use the character of the type which you want back. You could use @foo[1..3] for a slice of three elements of @foo, or even @foo{A,B,C} for a slice of of %foo. This is the same as using ($foo[1], $foo[2], $foo[3]) and ($foo{A}, $foo{B}, $foo{C}) respectively. In fact, you can even use lists to subscript arrays and pull out more lists, like @foo[@bar] or @foo{@bar}, where @bar is in both cases presumably a list of subscripts.

Other resources at this site: