简体   繁体   English

如何访问数组Perl中的每个元素

[英]How to access each element in an array Perl

my@arr=qw(Larrywall); 

This is my array, but i want access only Y . 这是我的数组,但我只想访问Y How to do this please let me know. 如何做到这一点,请让我知道。 Good answers will be appreciable. 好的答案将是可观的。

qw(Foo Bar) is the same as ('Foo', 'Bar') . qw(Foo Bar)('Foo', 'Bar')

with my @arr = qw(Larrywall) you create an array with one element. my @arr = qw(Larrywall)创建一个只有一个元素的数组。 If you would like to iterate through every character of your string, you have to split it into characters: 如果要遍历字符串中的每个字符,则必须将其拆分为字符:

my @arr = split //, "LarryWall";

The // part is the regex on which you want to split your string. //部分是要在其上分割字符串的正则表达式。 In this case we use the empty pattern which always matches, so it will essentially split on every character. 在这种情况下,我们使用始终匹配的空模式,因此它将基本上在每个字符上分割。

If you have an array and you want to split each element into its characters, you could do something like this: 如果您有一个数组,并且想要将每个元素分成其字符,则可以执行以下操作:

my @arr = map { split //, $_ } qw(Larry Wall SomethingElse);
#=> qw(L a r r y W a l l S o m e t h i n g E l s e)

or 要么

my @arr = map { [split //, $_] } qw(Larry Wall SomethingElse);
#=> ([qw(L a r r y)], [qw(W a l l)], [qw(S o m e t h i n g E l s e)])

Use substr on the array's only element: 在数组的唯一元素上使用substr

use strict;
use warnings;

my @arr = qw(Larrywall);
print substr $arr[0], 4, 1;

Output: 输出:

y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM