微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Learning Perl: 3.1. Accessing Elements of an Array

Previous Page

Next Page

 

3.1. Accessing Elements of an Array

If you've used arrays in another language,you won't be surprised to find Perl provides a way to subscript an array to refer to an element by a numeric index.

The array elements are numbered using sequential integers,beginning at zero and increasing by one for each element,like this:

@H_502_30@ $fred[0] = "yabba"; $fred[1] = "dabba"; $fred[2] = "doo";

The array name (in this case,"fred") is from a completely separate namespace than scalars use. You Could have a scalar variable named $fred in the same program. Perl treats them as different things and doesn't get confused.[*] (Your maintenance programmer might be confused though,so don't capricIoUsly make all of your variable names the same.)

[*] The Syntax is always unambiguous; tricky perhaps,but unambiguous.

You can use an array element like $fred[2] in every place[

] where you Could use any other scalar variable like $fred. For example,you can get the value from an array element or change that value by the same sorts of expressions we used in the prevIoUs chapter:

[

] Well,almost. The most notable exception is that the control variable of a foreach loop,which you'll see later in this chapter,must be a simple scalar. And there are others,like the "indirect object slot" and "indirect filehandle slot" for print and printf.

@H_502_30@ print $fred[0]; $fred[2] = "diddley"; $fred[1] .= "whatsis";

Of course,the subscript may be any expression that gives a numeric value. If it's not an integer,it'll automatically be truncated to the next lower integer:

@H_502_30@ $number = 2.71828; print $fred[$number - 1]; # Same as printing $fred[1]

If the subscript indicates an element that would be beyond the end of the array,the corresponding value will be undef. This is the same as ordinary scalars; if you've never stored a value into the variable,it's undef.

@H_502_30@ $blank = $fred[ 142_857 ]; # unused array element gives undef $blanc = $mel; # unused scalar $mel also gives undef

Previous Page

Next Page

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐