Программисты на Perl должны уметь эффективно пользоваться сложными типами данных. В этой статье собраны наиболее полезные посты с сайта PerlMonks, и показаны примеры использования сложных типов данных. По идее, сведений в этой статье должно быть достаточно, но при необходимости можно перейти по ссылке на англоязычный сайт PerlMonks.
1. Массив массивов в Perl
Как определить массив массивов:
@tgs = ( ['article series', 'sed & awk', 'troubleshooting', 'vim', 'bash'], ['ebooks', 'linux 101', 'vim 101', 'nagios core', 'bash 101' ] );
Обратиться к отдельному элементу, к примеру ко второму элементу первого массива, можно так:
$tgs[0][1];
Обратиться к каждому элементу один за одним:
print @$_, "\n" foreach ( @tgs );
Подробности: How do I make an array of arrays?
2. Хеш хешей в Perl
Определяем хеш хешей:
%tgs = ( 'articles' => { 'vim' => '20 awesome articles posted', 'awk' => '9 awesome articles posted', 'sed' => '10 awesome articles posted' }, 'ebooks' => { 'linux 101' => 'Practical Examples to Build a Strong Foundation in Linux', 'nagios core' => 'Monitor Everything, Be Proactive, and Sleep Well' } );
Обратиться к отдельному элементу хеша:
print $tgs{'ebooks'}{'linux 101'};
Подробности: How do I make a hash of hashes?
3. Хеш массивов Perl
Хеш массивов можно определить так:
%tgs = ( 'top 5' => [ 'Best linux OS', 'Best System Monitoring', 'Best Linux Text editors' ], '15 example' => [ 'rpm command', 'crontab command', 'Yum command', 'grep command' ], );
Обратиться ко всем элементам поочередно:
foreach my $key ( keys %tgs ) { print "Articles in group $key are: "; foreach ( @{$tgs{$key}} ) { print $_; } }
Подробности: How do I make a hash of arrays?
4. Создаем стек Perl
Создать стек в Perl очень просто – нужно воспользоваться структурой “массив” и функциями push и pop.
Во-первых, определим массив вот так:
@array = ( 1, 2, 3, 4, 5 );
Операции со стеком:
push ( @array, 6 ); # помещает элемент 6 на верхушку стека. pop ( @array ); # возвращает верхний элемент 6.
Подробности: How do I make a stack?
5. Визуализируем сложные типы данных Perl
При работе с кодом, работающим со сложными структурами данных, зачастую не обойтись без визуализации этих данных. В этих случаях можно воспользоваться модулем Dumper, как показано ниже:
use Data::Dumper; print Dumper $ref;
Этот код отобразит структуру данных $ref в удобном для восприятия виде:
$VAR1 = { 'a' => [ { 'A' => 1, 'B' => 2 }, { 'D' => [ 4, 5, 6 ], 'C' => [ 1, 2, 3 ] } ] };
Из этого вывода можно ясно видеть, где массив, где хеш, и зависимости между ними. Весьма удобно при отладке программ на Perl.
Подробности: How can I visualize my complex data structure?
I’m impressed, I have to admit. Truly rarely should i encounter a blog that’s both educative and entertaining, and let me tell you, you might have hit the nail around the head. Your notion is outstanding; the thing is an issue that there are not enough consumers are speaking intelligently about. I am very happy i found this in my look for something in regards to this.
I went over this website and I believe you have a lot of wonderful information, saved to my bookmarks (:.
I am really enjoying the theme/design of your blog.
Do you ever run into any browser compatibility issues? A few of my blog audience have
complained about my blog not working correctly in Explorer but looks great in Safari.
Do you have any ideas to help fix this issue?
I am no longer certain where you’re getting your info, however good topic.
I must spend some time learning more or working
out more. Thanks for fantastic info I used to be in search of this
info for my mission.
I am glad to read this post, it’s an impressive one. I am always searching for good posts and articles and this is what I found here, I hope you will be adding more in future.
Wow! At last I got a webpage from where I can actually take helpful
facts regarding my study and knowledge.