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?

你可能感兴趣的:(linux,command,perl,Access,dependencies,nagios)