Perl Tips
1. Basic
│ my @myarray = (); │ push @myarray,"a";
│ my @keys = qw(a b c); │ my @vals = (1, 2, 3); │ my %hash; │ @hash{@keys} = @vals;
2. Loop
│ # loop elements in itemArray1 and itemArray2 │ foreach my $item (@itemArray1, @itemArray2) { │ ... │ } │ │ while ( my ($key, $value) = each(%hash) ) { │ print "$key => $value\n"; │ }
3. Sub
│ sub prepare_sth { │ my $param = shift; # means shift @_, @_ is param array │ # my $param = $_; # when could use $_ ?? │ }
│ sub uniq { │ @list = shift; │ %seen = (); │ @uniqu = grep { ! $seen{$_} ++ } @list; │ }
4. Data Structure
4.1. AoA
from book
│ ### Assign a list of array references to an array. │ @AoA = ( │ │ [ "fred", "barney" ], │ │ [ "george", "jane", "elroy" ], │ │ [ "homer", "marge", "bart" ], │ ); │ print $AoA[2][1]; # prints "marge" │ │ ### Create an reference to an array of array references. │ $ref_to_AoA = [ │ │ [ "fred", "barney", "pebbles", "bamm bamm", "dino", ], │ │ [ "homer", "bart", "marge", "maggie", ], │ │ [ "george", "jane", "elroy", "judy", ], │ ]; │ │ print $ref_to_AoA->[2][3]; # prints "judy"
Remember that there is an implied -> between every pair of adjacent braces or brackets. (Simply saying, -> indicates a reference which created via []).
Therefore these two lines:
│ $AoA[2][3] │ $ref_to_AoA->[2][3]
are equivalent to these two lines:
│ $AoA[2]->[3] │ $ref_to_AoA->[2]->[3]