all that's code
regex debugging

use re ‘debug’;

my $sentence = ‘this apple pie is excellent’;
print “it matched\n” if $sentence =~ /(pie|apple)/;

simple index

print “provide a test string: “;
chomp( my $string = <STDIN> );

print ” … and a substring: “;
chomp( my $substring = <STDIN> );

my @foundings;

for ( my $hol = -1;;) {
     $hol =index($string, $substring, $hol+1);
     # precedes push, as -1 should not be in @foundings
     last if $hol == -1;   
     push @foundings,$hol;
}

say “@foundings”;

RUN:
provide a test string: somewhere someplace someone
   … and a substring: some

OUTPUT: 0 10 20
Closures

sub make_iterator {
      my @items = @_;
      my $count = 0;

      return sub {  # returning an anon-sub
                        return if $count == @items;
                        return $items[ $count++ ];
                     }

}

my $cousins = make_iterator( qw/111 222 333 444 555 666 777/ );

say $cousins->() for 1 .. 5;

OUTPUT:
111
222
333
444
555

Now adding another iteration:  

my $aunts = make_iterator( qw/aaa bbb ccc ddd eee fff/ );

say $cousins->();
say $aunts->();

OUTPUT:
666
aaa 
Check operator precedence with B::Deparse

The core B::Deparse module is an invaluable debugging tool. Run

perl -MO=Deparse,-p

on a snippet of code to see exactly how Perl handles operator precedence and associativity. The -p flag adds extra grouping parentheses which often clarify evaluation order.

actual code:

for ( sort keys %vscan_status ) {
 print “$_ ===> $vscan_status{ $_ }\n”;    
}

after perl -MO=Deparse,-p
foreach $_ (sort(keys(%vscan_status))) {
    print(“$_ ===> $vscan_status{$_}\n”);
}
Reference into arrays and hashes

my @new_array = @{ $array_ref };

my %new_hash = %{ $hash_ref };

Merging hashes with slice

my %addresses = ( … );
my %canada_addresses = ( … );

@addresses{ keys %canada_addresses }= values %canada_addresses;

$” - List Separator

An useful built-in variable that I keep forgetting:

my @list = ( 1..7 );

$” = ‘][‘;
say “[@list]”;

OUTPUT:
[1][2][3][4][5][6][7] 

initializing hash slices

my %hash;
my @keys = qw(perls before swine);

@hash{@keys} = (“”) x @keys;

same as:

$hash{perls} = “”;
$hash{before} = “”;
$hash{swine} = “”;

horgoldenembuzi:

• The Art of Computer Programming, by Donald Knuth, Volumes 1–4A: “Fundamental

Algorithms,” “Seminumerical Algorithms,” “Sorting and Searching,”

and “Combinatorial Algorithms”; Addison-Wesley (2011).

xxxvi | Preface

• Introduction to Algorithms, by Thomas Cormen, Charles Leiserson, and Ronald

simple but useful subroutines

# One argument is true

sub any { $_ && return 1 for @_; 0 }

# All arguments are true

sub all { $_ || return 0 for @_; 1 }

# All arguments are false

sub none { $_ && return 0 for @_; 1 }

# One argument is false

sub notall { $_ || return 1 for @_; 0 }

# How many elements are true

sub true { scalar grep { $_ } @_ }

# How many elements are false

sub false { scalar grep { !$_ } @_ }