数组在另一个数组perl中

时间:2018-11-22 10:34:20

标签: perl

my @ana = ("Godfather", "Dirty Dancing", "Lord of the Rings", "Seven", "Titanic");
my @dana = ("American Pie", "Harry Potter", "Bruce Almighty", "Jaws 1", "Solaris");
my @mihai = ("Fight Club", "Gladiator", "Troy", "Eternal Sunshine of the Spotless Mind", "Lord of the Rings");
my @daniel = ("Independence Day", "Finding Nemo", "Gladiator", "Godfather", "Schindler’s List");

my @structure = (@ana,@dana,@mihai,@daniel);

如何从@structure获得一部电影?

my $subarray = @{$structure[3]}[3];

此行不起作用,我需要有关此语法的更多信息

3 个答案:

答案 0 :(得分:5)

数组在列表上下文中被展平,因此您的@structure包含@ana元素,然后是@dana等元素。使用数组引用嵌套数组:

my @structure = (\@ana, \@dana, \@mihai, \@daniel);
my $movie = $structure[3][3];

答案 1 :(得分:1)

要备份choroba的答案,您可以从perldoc perllolperldoc perldsc获得有关在Perl中构建复杂数据结构的更多信息。

答案 2 :(得分:1)

Perl中没有多维数组。您可以使用数组引用的数组来模拟这种行为。

@foo = ('one','two');                                                                                                                                                                          
@bar = ('three', 'four');
# equivalent of @baz = ('one','two','three', 'four');
@baz = (@foo, @bar);

# you need to store array references in @baz:
@baz = (\@foo, \@bar);
# Perl have a shortcut for such situations (take reference of all list elements):
# @baz = \(@foo, @bar);

# so, we have array ref as elements of @baz;

print "First element: $baz[0]\n";
print "Second element: $baz[1]\n";

# references must be dereferenced with dereferencing arrow

print "$baz[0]->[0]\n";
# -1 is a shortcut for last array element
print "$baz[1]->[-1]\n";

# but Perl knows that we can nest arrays ONLY as reference,
# so dereferencing arrow can be omitted

print "$baz[1][0]\n";

列表是临时列表,仅在定义的位置存在。您不能存储列表本身,但是可以存储列表的值,这就是列表不能嵌套的原因。 (1,2,(3,4))刚好相当于(1,2,3,4)

但是您可以通过以下方式获取列表的一部分:

print(
    join( " ", ('garbage', 'apple', 'pear', 'garbage' )[1..2] ), "\n"
);

如果@structure定义为标量值数组,则此语法没有意义:

    my @structure = (@ana,@dana,@mihai,@daniel);
    @{$structure[3]}[2];

您正在尝试取消引用字符串。始终在代码中使用stict和warning编译指示,这样您就不会出现此类错误:

# just try to execute this code
use strict;
use warnings;
my @ana = ("Godfather", "Dirty Dancing", "Lord of the Rings", "Seven", "Titanic");
my @structure = (@ana);                                                                                                                                                                        

print @{$structure[0]}, "\n";

正确用法:

use strict;
use warnings;
my @ana = ("Godfather\n", "Dirty Dancing\n", "Lord of the Rings\n", "Seven\n", "Titanic\n");
my @structure = (\@ana);

# dereference array at index 0, get all it's elements
print @{$structure[0]};
print "\n";

# silly, one element slice, better use $structure[0][1];
print @{$structure[0]}[1];

print "\n";
# more sense
print @{$structure[0]}[2..3];

您可以在这里阅读更多内容:

perldoc perlref
perldoc perllol

Perl的文档是我见过的最好的文档,看看吧,玩得开心!