2012年6月14日星期四

Perl的复杂数据结构

1.       Perl 参考/论坛http://www.perlmonks.org/?

2.       数组大小

$arraySize = @array;

$arraySize = scalar (@array);

$arraySize = $#array + 1;

   内部数组大小
   print $#{$numbersTwo [1]}+1, "\n";
print $#{$numbersThree[1][3]}+1, "\n";
 

判断数组某元素是否存在

exists $array{$i}

where $array[$i] is the $ith element of the @array. It returns false if you deleted the element with delete and true if you initialized the element withundef or with any other value.

#!/usr/local/bin/perl
   
use strict;
use warnings;
   
my @array = (1..5);
delete $array[2];
  print "\@array has ", $#array+1, " elements\n";
  # it prints @array has 5 elements
 
foreach (0..$#array) {
    print $array[$_], ' ' if exists $array[$_];
}
print "\n";
  # it prints: 1 2 4 5

 

判断子过程是否存在

exists &subroutine


It returns true if the subroutine was declared and false otherwise.

The following short code snippet shows how you can use the Perl existsfunction with subroutines:

#!/usr/local/bin/perl

 

use strict;

use warnings;

 

sub subtract;

sub add {

  return shift() + shift();

}

 

print "divide doesn't exist\n" if !exists ÷

print "subtract exists\n" if exists &subtract;

print "subtract it's not defined\n" if !defined &subtract;

print "add is defined\n" if defined &add;

print "5 + 7 = ", &add(5,7), "\n" if(defined &add);

 

3.       哈希

一维哈希
     %ages = ("John", 43, "Paul", 25, "Marie", 22);
        %members = (John => "father", Paul => "son", 
                        Marie => "daughter");

拷贝哈希

        %destHash = %sourceHash;  # copy a hash
          $destHasRef = $sourceHashRef;  # copy a hash ref

清空哈希

        %hash = ();

判断是否存在某key

        exists $hash{$key}
 
        #!/usr/local/bin/perl
        use strict;
 use warnings;
 
my (%hash, $key);
%hash = ( 1 => 'one', 2 => 'two',
            3 => 'three', 4 => 'four', 5 => undef );
            
print "found 1\n" if exists $hash{1};
print "found 5\n" if exists $hash{5};
  print "the key 6 doesn't exist\n" if !exists $hash{6};
  exists $hash{7} || print "the key 7 doesn't exist\n";
exists $hash{$key}

 

抽取哈希表的部分

# define a hash
  %cds = ("Dr. Hook"         => "Sylvias Mother", 
              "Rod Stewart"    => "Maggie May", 
              "Andrea Bocelli"  => "Romanza",
              "Kenny Rogers"  => "For the good times",
              "Bee Gees"        => "One night only",
              "Bonnie Tyler"    => "Hide your heart"); 
   
# we used the @ prefix because the return value
# represents a list
  # we need to supply the keys for which we wanted 
# to extract the values 
@slice = @cds{"Dr. Hook","Kenny Rogers","Bee Gees"}; 
# we used the join function to print each string
  # on a new line 
print join("\n", @slice);
输出为
Sylvias Mother
  For the good times
One night only

遍历哈希表

%phoneNumbers = ("Anne", "432566", "Paul", "231275", "Marie", 
                 "299302");
  while (($key, $value) = each %phoneNumbers)
{
  print "$key has the phone number $phoneNumbers{$key}\n";
}
按键值来输出
foreach $key (keys %notebookPrices)
  {
  print "Key: $key, Value: \$$notebookPrices{$key}\n";
}
key值排序输出
# define a hash
  %time = (hour => 12, min => 25, sec => 32, msec =>75);
   
# foreach loop
foreach $key (sort keys %time)
  {
  print "$key: $time{$key}\n";
}
  value值排序输出
# define a hash
  %v = (v1 => 75, v2 => 251, v3 => 3, v4 => 12);
   
# sort by value and put the keys in an array 
@keys = sort {$v{$b} <=> $v{$a}} keys %v;
   
# loop through array to print the hash pairs ordered
foreach $key (@keys)
  {
  print "$key: $v{$key}\n";
}
   
 

哈希表插入新的 key-value

$hash{"key"} = "value";

哈希表删除已有key-value

delete $hash{$key};
  delete $hashRef->{$key};   # if you have a hash reference
  delete $$hashRef{$key};    # if you have a hash reference

 

翻转哈希表

# define a hash

%cds = ("Dr. Hook"       => "Sylvias Mother", 
        "Andrea Bocelli" => "Romanza",
        "Bonnie Tyler"   => "Hide your heart"); 
%cdsReversed = reverse %cds;
   
# we'll use Data::Dumper module to see 
# what it is in the hash
  use Data::Dumper;
print Dumper(\%cdsReversed);
将输出
$VAR1 = {
            'Sylvias Mother' => 'Dr. Hook',
            'Hide your heart' => 'Bonnie Tyler',
            'Romanza' => 'Andrea Bocelli'
          };
 

 

4.       Perl复杂结构体

http://www.thegeekstuff.com/2011/09/perl-complex-data-structures/

数组的数组、 哈希的哈希、数组的哈希、栈。可视化复杂结构体(Data::Dumper

5.       数组的数组

@array=( ["Homer","Marge","Bart","Lisa","Maggie"], ["Ned","Maude","Rod","Todd"] );

foreach my $ref(@array){

print "This family consists of: ";

foreach(@$ref){ print "$_ "; }

print "\n";

}

 

6.       Perl学习http://www.llc.manchester.ac.uk/intranet/ug/useful-links/perl/

 The Perl data structures described in this eBook include: arrays of arraysarrays of hashes,hashes of arrayshashes of hashes and other complex data structures.

If you take your time to skim through the Table of Contents of this eBook, you'll see what you should expect to find here. For every data structure I give you a lot of examples about how to generate,accessprintappendinsertremovereplacesort,copysearch or filter its elements.

In the same time you'll find a lot of example about how to use some important built-in functions with these structures. There are shown alternatives to iterate through these structure by using whileforforeachmap or grep. You'll find here a lot of commented examples to help you find a quick solution to your problem.

The examples included in this eBook are not only about complex data structures, but also show you how to use these structures together with operators, functions, subroutines, special variables, statements, regular expressions or with special notations as @$_, %{}, ||, &&, =>, @{}, [], {}, $_, $".

Complete solutions are provided for almost all the examples. Each example can be tested, modified and run individually. Every example shows you a way to resolve a specific problem, allowing you to find out a quick answer to your problem or question.


Now You Can Save Time And Find In Minutes The Answer To Your Question

If you want to improve your programming skill regarding the use of the complex data structures in different contexts, you'll find real help in this eBook. I chose for you the most frequent questions and I illustrated them with the appropriate examples.

Of course you can continue searching through the forums to find the answer of your question but in this case you need to choose, test and interpret yourself the information provided there.

In this eBook I give you a lot of working code that you can implement in minutes in your script. And not only that, all the provided code snippets are fully functional, i.e can be copied and tested in your command line window. Next, they can be integrated in a script and uploaded to your site.

In order to make the scripts very easy to understand, I commented in detail each code snippet so you will not have any problem to understand and implement it. 

Table Of Contents

I think you can use this eBook to find out very fast how to use the Perl complex data structures in different situations.

Please take a look at the table of contents to see what I mean:

1.

Copyright

2.

Introduction

  2.1.

How to run the examples included in this eBook

    2.1.1.

How to run the script in Windows

    2.1.2.

How to run the script in Linux

  

 

3.

Perl Complex Data Structures

  

 

  3.1.

Array of Arrays (@AoA)

    3.1.1.

How to generate an array of arrays:

      3.1.1.1.   

  - using while

      3.1.1.2.

  - using map

      3.1.1.3.

  - from a csv file

      3.1.1.4.

  - from a matrix contained in a text file

    3.1.2.

How to traverse and print an array of arrays:

      3.1.2.1.

  - using for

      3.1.2.2.

  - using foreach

      3.1.2.3.

  - using grep

      3.1.2.4.

  - using map

      3.1.2.5.

  - using while

    3.1.3.

How to acces/modify the inner arrays elements

    3.1.4.

How to find the length of an array of arrays

    3.1.5.

How to find a specific string/substring in all inner arrays

    3.1.6.

How to join into a string the elements of a particular inner array

    3.1.7.

How to join into a string the elements of a matrix column

    3.1.8.

Turn each inner array into a string and get an array with all these strings

    3.1.9.

How to sort an array of arrays

    3.1.10.

How to sort a matrix by multiple columns

    3.1.11.

How to remove the first column from a matrix

    3.1.12.

How to remove the last column from a matrix

    3.1.13.

How to remove the first row from a matrix

    3.1.14.

How to remove the last raw from a matrix

    3.1.15.

How to clear an array of arrays

    3.1.16.

How to insert a column at the beginning of a matrix

    3.1.17.

How to insert a row at the beginning of a matrix

    3.1.18.

How to append a column to a matrix

    3.1.19.

How to append a row to a matrix

    3.1.20.

How to read a text file and push into columns

    3.1.21.

How to replace/remove in a matrix a contiguous slice of columns

    3.1.22.

How to get slices from an array of arrays

    3.1.23.

How to copy an array of arrays – shallow vs deep

    3.1.24.

How to pass an array of arrays reference to a subroutine

    3.1.25.

How to deal with autovivification in an array of arrays

  

 

  3.2.

Array of Hashes (@AoH)

    3.2.1.

How to generate an array of hashes

    3.2.2.

How to traverse and print an array of hashes:

      3.2.2.1.

  - using for

      3.2.2.2.

  - using foreach

      3.2.2.3.

  - using grep

      3.2.2.4.

  - using map

      3.2.2.5.

  - using while

    3.2.3.

How to acces/modify the inner hashes elements

    3.2.4.

How to get an inner hash when a certain condition is met

    3.2.5.

How to extract the keys from an array of hashes

    3.2.6.

How to sort an array of hashes

    3.2.7.

How to remove the first element of an array of hashes

    3.2.8.

How to remove the last element of an array of hashes

    3.2.9.

How to delete a particular inner hash entry

    3.2.10.

How to clear the array of hashes

    3.2.11.

How to insert an element at the first position of an array of hashes

    3.2.12.

How to append an element to an array of hashes

    3.2.13.

Replace or remove a contiguous range of elements in an array of hashes

    3.2.14.

How to copy an array of hashes – shallow vs deep

    3.2.15.

How to pass an array of hashes reference to a subroutine

    3.2.16.

How to deal with autovivification in an array of hashes

  

 

  3.3.

Hash of Arrays (%HoA)

    3.3.1.

How to generate a hash of arrays

    3.3.2.

How to traverse and print a hash of arrays:

      3.3.2.1.

  - using for

      3.3.2.2.

  - using foreach

      3.3.2.3.

  - using grep

      3.3.2.4.

  - using map

      3.3.2.5.

  - using while

    3.3.3.

How to acces/modify the inner arrays elements

    3.3.4.

Get the hash keys whose corresponding inner arrays match a certain criteria

    3.3.5.

How to sort a hash of arrays

    3.3.6.

How to remove the first element of each inner array

    3.3.7.

How to remove the last element of each inner array

    3.3.8.

How to delete a particular hash entry

    3.3.9.

How to clear a hash of arrays

    3.3.10.

How to insert new elements in front of a particular inner array

    3.3.11.

How to append new elements to a particular inner array

    3.3.12.

How to concatenate two matrices

    3.3.13.

How to copy a hash of arrays – shallow vs deep

    3.3.14.

How to pass a hash of arrays reference to a subroutine

    3.3.15.

How to deal with autovivification in a hash of arrays

  

 

  3.4.

Hash of Hashes (%HoH)

    3.4.1.

How to generate a hash of hashes

    3.4.2.

How to traverse and print a hash of hashes:

      3.4.2.1.

  - using for

      3.4.2.2.

  - using foreach

      3.4.2.3.

  - using grep

      3.4.2.4.

  - using map

      3.4.2.5.

  - using while

    3.4.3.

How to access/modify an inner hash element

    3.4.4.

How to add another anonymous hash to a hash of hashes

    3.4.5.

How to represent a matrix as a hash of hashes

    3.4.6.

How to find the length of a hash of hashes

    3.4.7.

How to count the occurrences of a particular value in all inner hashes

    3.4.8.

Get and sort the values associated with a specific key in the inner hashes

    3.4.9.

How to sort a hash of hashes

    3.4.10.

How to delete an entry from an inner hash

    3.4.11.

How to delete a specific entry of a hash of hashes

    3.4.12.

How to clear a hash of hashes

    3.4.13.

How to copy a hash of hashes – shallow vs deep

    3.4.14.

How to pass a hash of hashes reference to a subroutine

    3.4.15.

How to deal with autovivification in a hash of hashes

  

 

  3.5.

More elaborate records

    3.5.1.

How to store multiple values to a single hash key

    3.5.2.

How to print a %HoHoH (a hash of hashes of hashes)

    3.5.3.

How to access complex data structures using a recursive subroutine

    3.5.4.

How to copy complex data structures – shallow vs deep

    3.5.5.

How to deal with autovivification in complex data structures

    3.5.6.

Hash of Functions


And as a bonus, I give you a "Perl Glossary" eBook to help you better understand the topics included in my tutorial.

没有评论: