In Perl, what is the difference between accessing an array element using @a[$i] as opposed to using $a[$i]?

后端 未结 3 960
臣服心动
臣服心动 2020-12-04 02:19

Basic syntax tutorials I followed do not make this clear:

Is there any practical/philosophical/context-dependent/tricky difference between accessing a

3条回答
  •  孤街浪徒
    2020-12-04 02:28

    If you turn on warnings (which you always should) you would see this:

    Scalar value @a[0] better written as $a[0]

    when you use @a[1].

    The @ sigil means "give me a list of something." When used with an array subscript, it retrieves a slice of the array. For example, @foo[0..3] retrieves the first four items in the array @foo.

    When you write @a[1], you're asking for a one-element slice from @a. That's perfectly OK, but it's much clearer to ask for a single value, $a[1], instead. So much so that Perl will warn you if you do it the first way.

提交回复
热议问题