use re ‘debug’;
my $sentence = ‘this apple pie is excellent’;
print “it matched\n” if $sentence =~ /(pie|apple)/;
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”;
… and a substring: some
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->();
666
aaa
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”;
}
foreach $_ (sort(keys(%vscan_status))) {print(“$_ ===> $vscan_status{$_}\n”);}
my %addresses = ( … );
my %canada_addresses = ( … );@addresses{ keys %canada_addresses }= values %canada_addresses;
An useful built-in variable that I keep forgetting:
my @list = ( 1..7 );
$” = ‘][‘;
say “[@list]”;
OUTPUT:
[1][2][3][4][5][6][7]
my %hash;
my @keys = qw(perls before swine);@hash{@keys} = (“”) x @keys;
same as:
$hash{perls} = “”;
$hash{before} = “”;
$hash{swine} = “”;
• 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
# 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 { !$_ } @_ }