Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

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

Basic syntax tutorials I followed do not make this clear:

Is there any practical/philosophical/context-dependent/tricky difference between accessing an array using the former or latter subscript notation?

$ perl -le 'my @a = qw(io tu egli); print $a[1], @a[1]'

The output seems to be the same in both cases.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$a[...]   # array element

returns the one element identified by the index expression, and

@a[...]   # array slice

returns all the elements identified by the index expression.

As such,

  • You should use $a[EXPR] when you mean to access a single element in order to convey this information to the reader. In fact, you can get a warning if you don't.
  • You should use @a[LIST] when you mean to access many elements or a variable number of elements.

But that's not the end of the story. You asked for practical and tricky (subtle?) differences, and there's one noone mentioned yet: The index expression for an array element is evaluated in scalar context, while the index expression for an array slice is evaluated in list context.

sub f { return @_; }

$a[ f(4,5,6) ]     # Same as $a[3]
@a[ f(4,5,6) ]     # Same as $a[4],$a[5],$a[6]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...