Массив в другом массиве Perl - PullRequest
0 голосов
/ 22 ноября 2018
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 голосов
/ 22 ноября 2018

Чтобы поддержать ответ Чоробы, вы можете получить больше информации о построении сложных структур данных в Perl из perldoc perllol и perldoc perldsc .

0 голосов
/ 24 ноября 2018

В 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 и warnings в вашем коде, и вы будете свободны от таких ошибок:

# 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 - лучшая документация, которую я когда-либо видел, посмотрите и повеселитесь!

0 голосов
/ 22 ноября 2018

Массивы сглаживаются в контексте списка, поэтому ваша структура содержит элементы @ana, за которыми следуют элементы @dana и т. Д. Используйте ссылки на массивы для вложенных массивов:

my @structure = (\@ana, \@dana, \@mihai, \@daniel);
my $movie = $structure[3][3];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...