Perl associative array (hash) and array

refer to : http://www.thegeekstuff.com/2011/09/perl-complex-data-structures/ and http://www.perlmonks.org/?node_id=1978


Perl developers should understand how to use complex data structures effectively.

In this article, I picked the top 5 useful posts about complex data structures from perlmonks, and gave simple examples on how to use them.
1. Perl Array of Arrays

The following example defines a sample perl array of arrays.
@tgs = (
['article series', 'sed & awk', 'troubleshooting', 'vim', 'bash'],
['ebooks', 'linux 101', 'vim 101', 'nagios core', 'bash 101' ]
);

To access a single element, for example, to Access 2nd element from the 1st array, do the following:
$tgs[0][1];

Access all the elements one by one as shown below.
print @$_, "\n" foreach ( @tgs );

Read more: How do I make an array of arrays?
2. Perl Hash of Hashes

The following example defines a sample perl hash of hashes.
%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'
}
);

To access a single element from hash, do the following.
print $tgs{'ebooks'}{'linux 101'};

Read more: How do I make a hash of hashes?
3. Hash of Arrays

The following example defines a sample perl hash of arrays.
%tgs = (
'top 5' => [ 'Best linux OS', 'Best System Monitoring', 'Best Linux Text editors' ],
'15 example' => [ 'rpm command', 'crontab command', 'Yum command', 'grep command' ],
);

To access all elements one by one, do the following.
foreach my $key ( keys %tgs ) {
print "Articles in group $key are: ";
foreach ( @{$tgs{$key}} ) {
print $_;
}
}

Read more: How do I make a hash of arrays?
4. Making a Stack

Making a stack is very simple in Perl using arrays with push & pop function.

First, define an array as shown below.
@array = ( 1, 2, 3, 4, 5 );

Stack operation:
push ( @array, 6 ); # pushes the content at the end of array.
pop ( @array ); # gives the top element 6.

Read more: How do I make a stack?
5. Visualize a Complex Perl Data Structure

When you see a code which builds complex data structure, to visualize it better, use Dumper as shown below.
use Data::Dumper;
print Dumper $ref;

The above code snippet will dump the output in a user friendly way as shown below.
$VAR1 = {
'a' => [
{
'A' => 1,
'B' => 2
},
{
'D' => [
4,
5,
6
],
'C' => [
1,
2,
3
]
}
]
};

From the above output, you can clearly tell which is array, which is hash, and the dependencies, etc.

Read more: How can I visualize my complex data structure?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值