Perl Data Structures Cookbook

use List::Util module

 

To create a collection of objects (e.g. hashes)

my @collection = ({%hash1},{%hash2})

For a hash,

$hash{key} and %hash->{key} are equivalent

Use foreach to modify content of a list

Use grep to filter a list

Use of map

Use map to transform one list to another

my ($from) = map /^From:\s+(.*)$/, @message_lines;

my @text_files = map { /(.*)\.txt$/ } @files;

Use map to transform elements of a data structure into a new structure

Use map and grep together for complex operations

Operation applied by map should not modify element
 

Removing duplicates from an array

my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @a;

Sorting a collection

Minimize call to function
 
Instead of using
my @sorted = sort { -M $a <=> -M $b } @files;
use
my @sorted =
sort { ( $m{$a} ||= -M $a ) <=> ( $m{$b} ||= -M $b ) }
@files;
where $m{$a} ||= -M $a keeps the cached value of -M in $m{$a}
 
 
Schwartzian Transform:
 
my @sorted_names =
map { $_->[0] }  # 4. extract original names
sort { $a->[1]
<=>
$b->[1] }            # 3. sort [name, key] tuples
map { [ $_, -M ] } # 2. create [name, key] tuples
@files;                 # 1. the input data
 
 

References

Take reference of array and change content
 
$ref = \@ary;
@$ref[1] = "new val";
 
These two are the same
 
$list_ref->[1];
@$list_ref[1];
 
Autovivification creates reference on the fly
 
$ary->[3] = 'NEW ELEMENT'
 
 
A Hash collection of array references
 
my %hash = (hash1=>[qw(item1 item2)],
           hash2=>[qw(item3 item4)],
           hash3=>[('item5')]);
foreach my $style (keys (%hash)) {
        say $style;
        my @filelist = @{$hash{$style}};
        foreach my $ele (@filelist) {
                say 'array element = ', $ele;
        }
}
 
A array collection of hash references
 
my %h1 = (id => 'A123', action => 'AMEND');
my %h2 = (id => 'A456', action => 'NEW');
my @a = ({%h1}, {%h2});
for (@a) {
        my %h = %$_;
        say $h{id};
        say $h{action};
}
}