The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Perl
1
Print a literal string on standard output
print "Hello, world!\n";
Alternative implementation:
say 'Hello World';
2
Loop to execute some code a constant number of times
print "Hello\n" for 1 .. 10;
Alternative implementation:
say "Hello" for 1 .. 10;
Alternative implementation:
print "Hello\n" x 10;
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
sub some_procedure {
    print 'some side effect';
    return;
}
4
Create a function which returns the square of an integer
sub square {
    my ($i) = @_;
    return $i ** 2;
}
5
Declare a container type for two floating-point numbers x and y
my $point = [ 1.5, 6.3 ];
Alternative implementation:
my $point = { x => 1, y => 2 };
6
Do something with each item x of an array-like collection items, regardless indexes.
do_something($_) for @items;
Alternative implementation:
for my $x (@items) {
     do_something($x);
     more_stuffs($x);
}
7
Print each index i with its value x from an array-like collection items
# For an array
while (my ($idx, $val) = each @array) {
    print "array[$idx] = $val\n";
}

# For a hash
while (my ($key, $val) = each %hash) {
    print "hash{$key} = $val\n";
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
my %x = ( 
    name => 'Roboticus',
    'foo bar' => 'joe'
);
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
class Tree::Binary {
    has 'left', is => 'ro', isa => Maybe[InstanceOf['Tree::Binary']];
    has 'right', is => 'ro', isa => Maybe[InstanceOf['Tree::Binary']];
    has 'val', is => 'ro', isa => Int;
}
my $t = Tree::Binary->new(
    val => 42,
    left => Tree::Binary->new(val => 23),
    right => Tree::Binary->new(
        val => 1729,
        right => Tree::Binary->new(val => -1)
    )
);
__END__
      42
    ↙    ↘
  23     1729
 ↙  ↘   ↙    ↘
∅    ∅ ∅     -1
10
Generate a random permutation of the elements of list x
@shuffled = shuffle(@x);
11
The list x must be non-empty.
my @x = ('a', 'list', 'of', 'random', 'items');
print $x[rand @x];
12
Check if the list contains the value x.
list is an iterable finite container.
print "Found 'foo'\n" if grep {$_ eq $x} @list;
Alternative implementation:
print "ok\n" if first {$_ eq $x} @list;
13
Access each key k with its value x from an associative array mymap, and print them.
while (my ($k, $x) = each %mymap) {
    print "Key=$k, Value=$x\n";
}
Alternative implementation:
printf "Key=%s, Value=%s\n",$_,$mymap{$_} foreach (sort keys %mymap);

14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
my ($min, $max) = (1.5, 7.2);
my $x = $min + rand($max-$min);
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
my ($min, $max) = (5, 25);
my $val = $min + int(rand($max-$min));
16
Call a function f on every node of binary tree bt, in depth-first infix order
sub dfs {
   my ($f, $bt) = @_;
   dfs($f, $bt->{left}) if exists $bt->{left};
   $f->($bt);
   dfs($f, $bt->{right}) if exists $bt->{right};
}
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
my $tree = {
           'Root' => {
                 'Child1' => {
                       'GrandChild1' => {},
                       'GrandChild2' => {}
                 },
                 'Child2' => {}
           }
};
18
Call a function f on every node of a tree, in depth-first prefix order
sub depth_first_traversal {
   my ($f, $treenode) = @_;
   $f->($treenode);
   depth_first_traversal($f, $_) for @{$treenode->{children}};
}
19
Reverse the order of the elements of list x.
This may reverse "in-place" and destroy the original ordering.
my @list = ('words', 'of', 'list', 'a', 'reverse');
my @reversed = reverse @list;
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
sub search {
   my ($x, $m) = @_;
   while ( ($k1,$v1) = each @$m ) {
      while ( ($k2, $v2) = each @$v1 ) {
           return $k1, $k2 if $v2 == $x;
      }
   }
}
21
Swap the values of the variables a and b
($a, $b) = ($b, $a);
22
Extract the integer value i from its string representation s (in radix 10)
my $i = $s + 0;
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
$s = sprintf "%.2f", $x;
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
my $s = 'ネコ';
25
Share the string value "Alan" with an existing running process which will then display "Hello, Alan"
my @queue :shared;

threads->create('my_task');
push @queue, 'Alan';
sleep 5;

sub my_task {
   while (1) {
      while (@queue) {
         print "Hello, ", (pop @queue), "\n";
      }
      sleep 1;
}

         
      
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
my @array = (
   [ 1.0, 0.0, 0.0 ],
   [ 0.0, 1.0, 0.0 ],
   [ 0.0, 0.0, 1.0 ],
   "first three slots are a 3x3 identity matrix",
   "fourth and fifth slots contain strings"
);
   
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
my $array3d = [
    [ [ 1, 0, 1 ],
      [ 0, 0, 0 ],
      [ 1, 0, 1 ] ],
    [ [ 0, 0, 0 ],
      [ 0, 2, 0 ],
      [ 0, 0, 0 ] ],
    [ [ 3, 0, 3, ],
      [ 0, 0, 0, ],
      [ 3, 0, 3, ] ]
];
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
@items = sort { $a->{p} cmp $b->{p} } @items;
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
# perl alters the original list with splice
$removed_element = splice @items, $i, 1;
30
Launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
for my $i (1 .. 1000) {
    threads->create('f', $i);
}
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
sub f {
   my $n = shift;
   return $n<2 ? 1 : $n * f($n-1);
}
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
sub exp {
   my ($x, $n) = @_;
   return 1 unless $n;
   return $x if $n == 1;
   return $x * exp($x*$x, ($n-1)/2) if $n%2;
   return exp($x*$x, $n/2);
}
Alternative implementation:
sub exp {
   my ($x, $n) = @_;
   return undef if $x < 0 or $n < 0;
   return $x ** $n;
}
33
Assign to the variable x the new value f(x), making sure that no other thread may modify x between the read and the write.
my $x :shared;
$x = 0;

sub my_task {
   my $id = shift;
   for (1 .. 5) {
      sleep 2*rand();
      { # lock scope
         lock($x);
         print "thread $id found $x\n";
         $x = $id;
         sleep 2*rand();
      }
   }
}

threads->create('my_task', $_) for 1 .. 3;
sleep 5 while threads->list(threads::running);
34
Declare and initialize a set x containing unique objects of type T.
class T {}
class Set::Object::T extends Set::Object {
    method BUILDARGS(T @items) { return {data => \@items}; }
    method insert(T @items) { $self->next::method(@items); }
}
my $x = Set::Object::T->new(T->new, T->new, T->new);
35
Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g ∘ f
sub compose {
   my ($f, $g) = @_;
   return sub {
      return $g->($f->(shift))
   }
}

sub double { return 2*shift }
sub triple { return 3*shift }
sub aFunc = compose(\&double, \&triple);
aFunc->(7);
36
Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.
sub compose {
   my ($f, $g) = @_;
   return sub {
      my $x = shift;
      return $g->($f->($x));
   }
}
37
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
sub curry {
   my ($func, $fixed_arg) = @_;
   return sub {
      $func->($fixed_arg, @_);
   }
}
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
my $chunk = substr("now is the time", $i, $j);
39
Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.
$ok = index($s,$word) >= 0;
40
Declare a Graph data structure in which each Vertex has a collection of its neighbouring vertices.
my $G = Graph::Undirected->new(edges => [
    [1,3], [2,4], [3,4], [3,5], [4,5]
]);
41
Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
my $s = 'cafe' . "\N{COMBINING ACUTE ACCENT}";
my $t = join '', reverse $s =~ /\X/g;
42
Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.
OUTER:
for my $v (@a) {
   for my $check (@b) {
      next OUTER if $v == $check;
   }
   print "$v not in the list\n";
}
      
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
OUTER: for my $row (@m) {
   INNER: for my $v (@$row) {
      if ($v < 0) {
         print "Negative value found: $v\n";
         last OUTER;
      }
   }
}
44
Insert element x at position i in list s. Further elements must be shifted to the right.
splice(@s, $i, 0, $x);
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
sleep 5;
46
Create string t consisting of the 5 first characters of string s.
Make sure that multibyte characters are properly handled.
my $t = substr($s,0,5);
47
Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.
use utf8;

my $t = substr($s, -5);
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
$s = "Perl normally allows
strings to contain newlines.";
Alternative implementation:
$s =<<EOSTR;
One of the ways to create multiline text is called
the "here doc" (lifted from various UNIX shells).
A 'here doc' is the <<tag construct.  Perl continues to treat
all the text found as part of the string until there's a line containing
the EOSTR tag at the beginning
EOSTR
Alternative implementation:
$s = q{
There are a good few ways to create multiline
text strings in perl.
};
49
Build list chunks consisting in substrings of input string s, separated by one or more space characters.
@chunks = split /\s+/, $s;
50
Write a loop that has no end clause.
while (1) {
   do_stuff();
}
Alternative implementation:
say "" while True;
51
Determine whether the map m contains an entry for the key k
exists $m->{$k}
52
Determine whether the map m contains an entry with the value v, for some key.
print "Found it!" if exists $m{$v};
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
$y = join(", ", @x)
54
Calculate the sum s of the integer list or array x.
$s = sum(@x);
55
Create the string representation s (in radix 10) of the integer value i.
my $s = "" . $i;
Alternative implementation:
$s = "$i";
56
Fork-join : launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
Wait for the completion of the 1000 tasks and then print "Finished".
for my $i (1 .. 1000) {
    threads->create('f', $i);
}
sleep 3 while threads->list(threads::running);
print "Finished\n";

# optional: threads library wants you to explicitly join or detach
# your threads before exiting program.
$_->join() for threads->list(threads::joinable);
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
# You can use a subroutine as your predicate
@primes_less_than_100 = grep { is_prime($_) } 1 .. 99;

# You can also write your predicate inline
@odd_numbers = grep { $_%2 == 1 } 1 .. 99;
58
Create string lines from the content of the file with filename f.
my $lines = do { local $/; <$FH> };
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
print STDERR "$x is negative";
60
Assign to x the string value of the first command line parameter, after the program name.
$x = $ARGV[0];
61
Assign to variable d the current date/time value, in the most standard type.
$d = time;
62
Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.
$i = index($x, $y);
63
Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.
my $x2 = $x =~ s/\Q$y/$z/gr;
64
Assign to x the value 3^247
$x = 3 ** 247;
65
From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
my $s = sprintf '%.1f%%', $x * 100;
66
Calculate the result z of x power n, where x is a big integer and n is a positive integer.
my ($x, $y) = (3 ** 200, 25);
my $z = $x ** $y;
67
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an integer type able to handle huge numbers.
sub binom {
   my ($n, $k) = @_;
   my $fact = sub {
      my $n = shift;
      return $n<2 ? 1 : $n * $fact->($n-1);
   };
   return $fact->($n) / ($fact->($k) * ($fact->($n-$k)));
}
Alternative implementation:
sub binom {
  my ($n, $k) = @_;
  if ($k > $n - $k) { $k = $n - $k }
  my $r = 1;
  for ( my $i = $n/$n ; $i <= $k;) {
    $r *= $n-- / $i++
  }
  return $r
}
68
Create an object x to store n bits (n being potentially large).
vec($x, $n, 1) = 0;
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
srand($s);
70
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
srand time;
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
print "@ARGV\n"
73
Create a factory named fact for any sub class of Parent and taking exactly one string str as constructor parameter.
sub fact {
    my ($class, $str) = @_;
    return $class->new($str) if $class->$_isa('Parent');
}
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
sub gcd {
    my ($A, $B) = @_;
    return 0 == $B
        ? $A
        : gcd($B, $A % $B);
}
75
Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.
sub gcd {
	my ($x, $y) = @_;
	while ($x) { ($x, $y) = ($y % $x, $x) }
	$y
}
 
sub lcm {
	my ($x, $y) = @_;
	($x && $y) and $x / gcd($x, $y) * $y or 0
}
Alternative implementation:
sub lcm {
	use integer;
	my ($x, $y) = @_;
	my ($f, $s) = @_;
	while ($f != $s) {
		($f, $s, $x, $y) = ($s, $f, $y, $x) if $f > $s;
		$f = $s / $x * $x;
		$f += $x if $f < $s;
	}
	$f
}
76
Create the string s of integer x written in base 2.

E.g. 13 -> "1101"
$s = sprintf "%b", $x;
77
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
my $x = 3*i - 2;
$x *= i;
Alternative implementation:
my $x = cplx(-2, 3);
$x *= i;
78
Execute a block once, then execute it again as long as boolean condition c is true.
do {
    doSomeStuff();
} while(c);
79
Declare the floating point number y and initialize it with the value of the integer x .
my $y = $x;
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
my $y = int($x);
81
Declare integer y and initialize it with the rounded value of floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
my $y = int($x + 1/2);
82
Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.
my $t="banana bo bana bandana";

my $c =()= $t=~ m/ana/g;
print "count without overlap: $c\n";

$c =()= $t =~ m/an(?=a)/g;
print "count with overlap: $c\n";
83
Declare regular expression r matching strings "http", "htttp", "httttp", etc.
my $r = qr/htt+p/;
84
Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2
# Not best, but simple:
$c=0;
while ($i) {
   $c += $i&1;
   $i /= 2;
}
85
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.
sub adding_will_overflow {
    my ($x, $y) = @_;
    return 'Inf' eq $x + $y;
}
86
Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

An overflow may be above the max positive value, or below the min negative value.
sub multiply_will_overflow {
    my ($x, $y) = @_;
    return 'Inf' eq $x * $y;
}
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
exit 0;
88
Create a new bytes buffer buf of size 1,000,000.
my $buf = ' ' * 1_000_000;
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
die "Invalid argument $x";
90
Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.
class Foo {
    lexical_has 'x', isa => Int, accessor => \(my $_x), default => 0;
    method x() { return $self->$_x }
    method increment_x() { $self->$_x(1 + $self->$_x) }
}
91
Read from the file data.json and write its content into the object x.
Assume the JSON data is suitable for the type of x.
my $str = read_file('data.json');
my $x = decode_json($str);
92
Write the contents of the object x into the file data.json.
write_file('data.json', encode_json($x));
93
Implement procedure control which receives one parameter f, and runs f.
sub control {
    my $f = shift;
    $f->();
}
94
Print the name of the type of x. Explain if it is a static type or dynamic type.

This may not make sense in all languages.
print ref($x)||"SCALAR", "\n";
95
Assign to variable x the length (number of bytes) of the local file at path.
my $x = -s $path;
96
Set boolean b to true if string s starts with prefix prefix, false otherwise.
$b = $prefix eq substr($s,0,length($prefix));
97
Set boolean b to true if string s ends with string suffix, false otherwise.
$b = $suffix eq substr($s, -length($suffix));
98
Convert a timestamp ts (number of seconds in epoch-time) to a date with time d. E.g. 0 -> 1970-01-01 00:00:00
my $d = DateTime->from_epoch(epoch => $ts)->strftime('%F %T');
99
Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.
$x = strftime "%Y-%m-%d", localtime($d);
100
Sort elements of array-like collection items, using a comparator c.
sub c {
 $a <=> $b;
}

my @result = sort c @items;

101
Make an HTTP request with method GET to URL u, then store the body of the response in string s.
my $s = HTTP::Tiny->new->get($u)->{content};
102
Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.
my $response = HTTP::Tiny->new->mirror($u, 'result.txt');
103
Read from the file data.xml and write its contents into the object x.
Assume the XML data is suitable for the type of x.
my $x = XML::LibXML->load_xml(
location => 'data.xml');
104
Write the contents of the object x into the file data.xml.
$x->toFile('data.xml');
105
Assign to the string s the name of the currently executing program (but not its full path).
my $s = $0;
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
my $dir = getcwd();
107
Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)
my $dir = path($EXECUTABLE_NAME)->parent;
108
Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
print $x if $x; # won't compile, see explanation
109
Set n to the number of bytes of a variable t (of type T).
my $n = total_size $t;
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
$blank = !$s || $s=~/^\s*$/;
111
From current process, run program x with command-line parameters "a", "b".
system $x, 'a', 'b';
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
for my $k (sort keys %mymap) {
    my $x = $mymap{$k};
    say "$k => $x";
}
113
Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.
sub by_val_then_key {
    return ($mymap{$a} <=> $mymap{$b})
        or ($a cmp $b)
}

for my $k (sort by_val_then_key keys %mymap) {
   print "$k: $mymap{$k}\n";
}

Alternative implementation:
for my $k (sort {($mymap{$a}<=>$mymap{$b}) or ($a cmp $b)}
           keys %mymap) {
   print "$k: $mymap{$k}\n";
}
114
Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y.
Tell if the code correctly handles recursive types.
my $b = Compare($x, $y);
115
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
my $b = d1 < d2;
116
Remove all occurrences of string w from string s1, and store the result in s2.
my $s2 = $s1 =~ s/\Q$w//gr;
117
Set n to the number of elements of the list x.
my $N = @x;
Alternative implementation:
$n = scalar @x;
118
Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.
my %y = map {$_=>0} @x;
Alternative implementation:
my @y = uniq @x;
119
Remove duplicates from the list x.
Explain if the original order is preserved.
@x = uniq(@x);
120
Read an integer value from the standard input into the variable n
my $n = <> + 0;  # read a line from STDIN, add 0 to convert to int
121
Listen UDP traffic on port p and read 1024 bytes into buffer b.
my $p = 55555;
my $socket = IO::Socket::IP->new(
    LocalHost => 'localhost',
    LocalService => $p,
    Type => SOCK_DGRAM,
);
while () {
    $socket->read(my $B, 1024);
}
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
my %suit = (
    SPADES   => 1,
    HEARTS   => 2,
    DIAMONDS => 3,
    CLUBS    => 4,
);
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert { is_consistent };
124
Write the function binarySearch which returns the index of an element having the value x in the sorted array a, or -1 if no such element exists.
sub binary_search {
    my ($x, $A, $lo, $hi) = @_;
    $lo //= 0;
    $hi //= @$A;
    my $mid = int($lo + ($hi - $lo) / 2);
    for ($x cmp $A->[$mid]) {
        use experimental 'switch';
        return $mid when 0;
        return -1 if 1 == $hi - $lo;
        return binary_search($x, $A, $lo, $mid) when -1;
        return binary_search($x, $A, $mid, $hi) when 1;
    }
}
125
measure the duration t, in nanoseconds, of a call to the function foo. Print this duration.
sub foo {};
my $start = Benchmark->new;
foo;
my $t = timediff(Benchmark->new, $start)->[0] * 10**9; 
126
Write a function foo that returns a string and a boolean value.
sub foo {
    return "bar", 1;
}
127
Import the source code for the function foo body from a file "foobody.txt".
sub foo {
    do './foobody.txt';
}
129
Call the function f on every vertex accessible from the vertex start, in breadth-first prefix order
my $iter = $tree->traverse($tree->LEVEL_ORDER);
while (my $v = $iter->()) {
    f($v);
}
130
Call th function f on every vertex accessible from the vertex v, in depth-first prefix order
my $iter = $tree->traverse;
while (my $v = $iter->()) {
    f($v);
}
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if ($c1)    { $f1 }
elsif ($c2) { $f2 }
elsif ($c3) { $f3 }
132
Run procedure f, and return the duration of the execution of f.
sub f {};
my $start = Benchmark->new;
f;
print timestr timediff(Benchmark->new, $start);
133
Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.
my $ok = $s =~ /\Q$word/i;
134
Declare and initialize a new list items, containing 3 elements a, b, c.
my @items = ($a, $b, $c);
135
Remove at most 1 item from list items, having value x.
This will alter the original list or return a new list, depending on which is more idiomatic.
If there are several occurrences of x in items, remove only one of them. If x is absent, keep items unchanged.
extract_first_by { $x eq $_ } @items;
136
Remove all occurrences of value x from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
my @filtered = grep { $x ne $_ } @items;
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
my $b = $s =~ /^\d*$/;
138
Create a new temporary file on the filesystem.
my $path = tempfile;
139
Create a new temporary folder on filesystem, for writing.
my $path = tempdir;
140
Delete from map m the entry having key k.

Explain what happens if k is not an existing key in m.
delete $m{$k}; # also succeeds when $k does not exist in %m
141
Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.
print for @items1, @items2;
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
my $s = sprintf("%x", $i);
143
Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.
print for zip @items1, @items2;
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
my $b = -f $fp;
145
Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.
my $logline = sprintf "%s %s\n", localtime->strftime('%F %T'), $msg;

print $logline; # stdout
warn $logline; # stderr
146
Extract floating point value f from its string representation s
my $f = $s;
147
Create string t from string s, keeping only ASCII characters
($t = $s) =~ s/[^\x00-\x7f]+//g;
148
Read a list of integer numbers from the standard input, until EOF.
@x = map {chomp; $_} <>;
150
Remove last character from string p, if this character is a slash /.
$p =~ s{/$}{};
151
Remove last character from string p, if this character is the file path separator of current platform.

Note that this also transforms unix root path "/" into the empty string!
chomp $p, File::Spec->catdir('');
152
Create string s containing only the character c.
my $s = $c;
153
Create the string t as the concatenation of the string s and the integer i.
my $t = "$s$i";
Alternative implementation:
my $t = $s . $i;
154
Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.
my @c1 = unpack 'xA2A2A2', $c1;
my @c2 = unpack 'xA2A2A2', $c2;
my $c = sprintf '#%02X%02X%02X', pairwise { (hex($a) + hex($b)) / 2 } @c1, @c2
155
Delete from filesystem the file having path filepath.
unlink $filepath;
156
Assign to the string s the value of the integer i in 3 decimal digits. Pad with zeros if i < 100. Keep all digits if i1000.
my $s = sprintf '%03d', $i;
157
Initialize a constant planet with string value "Earth".
const my $planet => 'Earth';
158
Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements.
Each element must have same probability to be picked.
Each element from x must be picked at most once.
Explain if the original ordering is preserved or not.
my @y = head $k, shuffle @x;
159
Define a Trie data structure, where entries have an associated value.
(Not all nodes are entries)
my $trie = Data::Trie->new;
160
Execute f32() if platform is 32-bit, or f64() if platform is 64-bit.
This can be either a compile-time condition (depending on target) or a runtime detection.
if ($Config{archname} =~ '64') {
    f64;
} else {
    f32;
}
161
Multiply all the elements of the list elements by a constant c
@elements = map {$_ * $c} @elements;
162
execute bat if b is a program option and fox if f is a program option.
for (@ARGV) {
    use experimental 'switch';
    bat when 'b';
    fox when 'f';
}
163
Print all the list elements, two by two, assuming list length is even.
foreach (pairs @list) {
   print "@$_\n";
}
164
Open the URL s in the default browser.
Set boolean b to indicate whether the operation was successful.
my $b = open_browser $s;
165
Assign to variable x the last element of list items.
my $x = $items[-1];
Alternative implementation:
my $x = $items[$#items];
166
Create the list ab containing all the elements of the list a, followed by all the elements of the list b.
@ab = (@a, @b)
167
Create string t consisting of string s with its prefix p removed (if s starts with p).
if (0 == index $s, $p) {
    my $t = substr $s, length $p;
}
168
Create string t consisting of string s with its suffix w removed (if s ends with w).
if (length $s == rindex($s, $w) + length $w) {
    my $t = substr $s, 0, rindex $s, $w;
}
169
Assign to integer n the number of characters of string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
my $n = length( $s );
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
my $n = keys %mymap;
171
Append element x to the list s.
push @s, $x;
172
Insert value v for key k in map m.
$m{$k} = $v;
173
Number will be formatted with a comma separator between every group of thousands.
 sub commify {
    local $_  = shift;
    1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
    return $_;
}
174
Make a HTTP request with method POST to URL u
perl -Mojo -E 'my $u = "www.example.com"; say p($u)->body;'
Alternative implementation:
# Create a user agent object

my $ua = LWP::UserAgent->new;
 
# Create a request
my $req = HTTP::Request->new(POST => $u);
 
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
 
# Check the outcome of the response
if ($res->is_success) {
    print $res->content;
}
else {
    print $res->status_line, "\n";
}
Alternative implementation:
my $response = `curl -X POST $u`;
175
From array a of n bytes, build the equivalent hex string s of 2n digits.
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
$s = unpack('H*', pack('c*', @a));
176
From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
my @a = split '', pack 'H*', $s;
177
Construct a list L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory D and all it's subdirectories.
my @L;
find(sub {
  push @L, $File::Find::name
     if /(.jpg|.jpeg|.png)$/;
}, $D);


178
Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.
sub insideRect($x1,$y1,$x2,$y2, $px,$py) {
    return
            $x1 <= $px and $px <= $x2
        and $y1 <= $py and $py <= $y1
}
179
Return the center c of the rectangle with coördinates(x1,y1,x2,y2)
my @c = (($x1 + $x2) / 2, ($y1 + $y2) / 2);
180
Create list x containing the contents of directory d.

x may contain files and subfolders.
No recursive subfolder listing.
opendir my $dh, $d or die "Could not open $d for reading: $!\n";
@x = readdir $dh;
closedir $dh;
Alternative implementation:
my @x = map {basename $_} glob("$d/*");
182
Output the source of the program.
$_=q(print"\$_=q($_);eval;");eval;
183
Make a HTTP request with method PUT to URL u
my $response = HTTP::Tiny->new->put($u, {content => $http_request_body});
184
Assign to variable t a string representing the day, month and year of the day after the current date.
my $dt = DateTime->today;
$dt->add(days => 1);
my $t = $dt->strftime('%F');
185
Schedule the execution of f(42) in 30 seconds.
local $SIG{ALRM} = sub { f(42) };
alarm 30;
Alternative implementation:
my $thr = threads->create(sub { sleep(30); f(42); });
$thr->detach();
Alternative implementation:
my $thr = threads->create(sub { sleep(30); f(42); });
$thr->join()
186
Exit a program cleanly indicating no error to OS
exit;
188
Perform matrix multiplication of a real matrix a with nx rows and ny columns, a real matrix b with ny rows and nz columns and assign the value to a real matrix c with nx rows and nz columns.
my ($nx, $ny, $nz) = (2, 3, 4);
my $A = sequence $ny, $nx;
my $B = sequence $nz, $ny;
my $C = matmult $A, $B;
189
Produce a new list y containing the result of function T applied to all elements e of list x that match the predicate P.
my @y = map { T($_) } grep { P($_) } @x;
190
Declare an external C function with the prototype

void foo(double *a, int n);

and call it, passing an array (or a list) of size 10 to a and 10 to n.

Use only standard features of your language.
FFI::Platypus
    ->new(lib => '/tmp/mylib/libmylib.so')
    ->attach(foo => ['double[]', 'int']);
foo([1..10], 10);
191
Given a one-dimensional array a, check if any value is larger than x, and execute the procedure f if that is the case
f if any { $_ > $x } @a;
192
Declare a real variable a with at least 20 digits; if the type does not exist, issue an error at compile time.
my $a = 12345678901234567890.1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890;
193
Declare two two-dimensional arrays a and b of dimension n*m and m*n, respectively. Assign to b the transpose of a (i.e. the value with index interchange).
my ($m, $n) = (3, 2);
my $A = sequence $m, $n;
my $B = transpose $A;
194
Given an array a, set b to an array which has the values of a along its second dimension shifted by n. Elements shifted out should come back at the other end.
my @a = (
    ['a' .. 'g'],
    ['h' .. 'm'],
    ['n' .. 'z']
);
my $n = 5;
my @b = map {
    my @c = @$_;
    push @c, splice @c, 0, $n;
    \@c;
} @a;
__END__
@b = (
    ['f', 'g', 'a' .. 'e'],
    ['m', 'h' .. 'l'],
    ['s' .. 'z', 'n' .. 'r']
)
195
Pass an array a of real numbers to the procedure (resp. function) foo. Output the size of the array, and the sum of all its elements when each element is multiplied with the array indices i and j (assuming they start from one).
sub foo {
    my ($A) = @_;
    my $i_size = @$A;
    my $j_size = max map { 0 + @$_ } @$A;
    printf "dimensions: %d %d\n", $i_size, $j_size;

    my $s;
    for my $i (1 .. $i_size) {
        for my $j (1 .. $j_size) {
            $s += $A->[$i - 1][$j - 1] * $i * $j;
        }
    }
    printf "sum: %f\n", $s;
}
196
Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.
sub foo  {
    my ($A, @i) = @_;
    @$A[@i] = (42) x @i;
    return $A;
}
foo($A, grep { 0 == $_ % 2 } 0 .. $m);
197
Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.
my @lines = path($path)->lines;
198
Abort program execution with error condition x (where x is an integer value)
exit $x;
199
Truncate a file F at the given file position.
my $F = path('F')->openrw;
# ... read some from $F to advance
# position of file handle (not shown) ...
truncate $F, tell $F;
200
Returns the hypotenuse h of the triangle where the sides adjacent to the square angle have lengths x and y.
my $h = hypot $x, $y;
201
Calculate n, the Euclidean norm of data (an array or list of floating point values).
my $data = [5.0, 4.0, 3.0, 2.0, 1.0];
my $n = gsl_blas_dnrm2(Math::GSL::Vector->new($data)->raw);
202
Calculate the sum of squares s of data, an array of floating point values.
my $s = sum map { $_ ** 2 } @data;
203
Calculate the mean m and the standard deviation s of the list of floating point values data.
my $m = mean @data;
my $s = stddev @data;
204
Given a real number a, print the fractional part and the exponent of the internal representation of that number. For 3.14, this should print (approximately)

0.785 2
my ($mantissa, $exponent) = frexp $a;
printf "%f %d\n", $mantissa, $exponent;
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
my $foo = $ENV{FOO} // 'none';
206
Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.
my %proc = map { $_ => \&$_ } qw(foo bar baz barfl);
$proc{$str}->() if exists $proc{$str};
207
Allocate a list a containing n elements (n assumed to be too large for a stack) that is automatically deallocated when the program exits the scope it is declared in.
{
    my @a = (undef) x $n;
    # scope ends at closing brace
} 
208
Given the arrays a,b,c,d of equal length and the scalar e, calculate a = e*(a+b*c+cos(d)).
Store the results in a.
$a[$_] = $e * ($a[$_] + $b[$_] * $c[$_] + cos $d[$_]) for 0 .. $#a;
209
Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable v of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).
class T {
    has 's', is => 'ro', isa => Str;
    has 'n', is => 'ro', isa => ArrayRef[Int];
}

{
    my $v = T->new(s => 'Hello, world!', n => [1,4,9,16,25]);
    # deallocation happens at closing brace, see explanation
}
210
Assign, at runtime, the compiler version and the options the program was compilerd with to variables version and options, respectively, and print them. For interpreted languages, substitute the version of the interpreter.

Example output:

GCC version 10.0.0 20190914 (experimental)
-mtune=generic -march=x86-64
my $version = $Config{version};
my $version_for_humans = $Config{version_patchlevel_string};
my %options = %Config{qw(config_args cccdlflags ccdlflags ccflags lddlflags libs)};
211
Create the folder at path on the filesystem
path($path)->mkpath;
212
Set boolean b to true if path exists on the filesystem and is a directory; false otherwise.
my $b = -e -d $path;
213
Compare four strings in pair-wise variations. The string comparison can be implemented with an equality test or a containment test, must be case-insensitive and must apply Unicode casefolding.
my @strings = ('ᾲ στο διάολο', 'ὰι στο διάολο', 'Ὰͅ ΣΤΟ ΔΙΆΟΛΟ', 'ᾺΙ ΣΤΟ ΔΙΆΟΛΟ');
my @indices = (
    [0,1], [0,2], [0,3],
    [1,0], [1,2], [1,3],
    [2,0], [2,1], [2,3],
    [3,0], [3,1], [3,2]
);
for my $tuple (@indices) {
    ok $strings[$tuple->[0]] =~ qr"\Q$strings[$tuple->[1]]"i;
}
done_testing;
215
Prepend extra character c at the beginning of string s to make sure its length is at least m.
The length is the number of characters, not the number of bytes.
$s = $c x ($m - length($s)) . $s;
216
Add extra character c at the beginning and ending of string s to make sure its length is at least m.
After the padding the original content of s should be at the center of the result.
The length is the number of characters, not the number of bytes.

E.g. with s="abcd", m=10 and c="X" the result should be "XXXabcdXXX".
my $total_padding = $m-length($s);
if( $total_padding ) {
   my $l = int($total_padding/2);
   my $r = $total_padding-$l;
   $s = join "", ($c x $l), $s, ($c x $r);
}
218
Create the list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.
my %u;
$u{$_} = 1 for @a, @b;
my @c = keys %u;
219
Create string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.
my $t = $s;
$t =~ s/ +/ /g;
Alternative implementation:
my $t = $s;
$t =~ s/\s+/ /g;
220
Create t consisting of 3 values having different types.

Explain if the elements of t are strongly typed or not.
use constant t => (1, 'two', 3.5);
221
Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
my $t = $s;
$t =~ s/\D+//g;
222
Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.
$i = -1;
$index = 0;
foreach (@items) {
    $i = $index, last if $x eq $items[$index];
    $index++;
}
223
Loop through list items checking a condition. Do something else if no matches are found.

A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.
my $found_match = 0;
foreach my $item (@items) {
    if ($item eq 4) {
        print "Found $item\n";
        $found_match = 1;
        last;
    }
}
if (!$found_match) {
    print "Didn't find what I was looking for\n";
}
224
Insert element x at the beginning of list items.
unshift @items, $x
225
Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise
sub f {
    my $x = shift;
    if (defined $x) {
        print("Present $x\n");
    }
    else {
        print("Not Present\n");
    }
}
226
Remove the last element from list items.
pop(@items);
227
Create the new list y containing the same elements as the list x.

Subsequent modifications of y must not affect x (except for the contents referenced by the elements themselves if they contain pointers).
my @y = @x; # for simple arrays

# for complex arrays with references:
my @y = @{dclone(\@x)};
228
Copy the file at path src to dst.
cp($src, $dst) or die $!;
232
Print "verbose is true" if the flag -v was passed to the program command line, "verbose is false" otherwise.
#!/usr/bin/perl -s

use strict;
use warnings;
use vars qw($v);

$v ||= 0;

print 'verbose is ' . ($v ? 'true' : 'false') . "\n";
233
Print the value of the flag -country passed to the program command line, or the default value "Canada" if no such flag was passed.
my $country = 'Canada';
GetOptions("country=s" => \$country) or die("Error in command line args\n");
print "Country is $country\n";
237
Assign to c the result of (a xor b)
my $c = $a ^ $b;
239
Assign to string x the first word of string s consisting of exactly 3 digits, or the empty string if no such match exists.

A word containing more digits, or 3 digits as a substring fragment, must not match.
my ($x) = $s =~ /\b(\d{3})\b/;
242
Call a function f on each element e of a set x.
f($_) for @x;
243
Print the contents of the list or array a on the standard output.
print "@items\n"; # delimited by spaced
print join(', ', @items) . "\n"; # delimited by what you want
244
Print the contents of the map m to the standard output: keys and values.
print "$_: $m{$_}\n" for keys %m;
246
Set c to the number of distinct elements in list items.
my $c = scalar(uniq @items);
247
Remove all the elements from list x that don't satisfy the predicate p, without allocating a new list.
Keep all the elements that do satisfy p.

For languages that don't have mutable lists, refer to idiom #57 instead.
@x = grep { p($_) } @x;
249
Define variables a, b and c in a concise way.
Explain if they need to have the same type.
my ($a, $b, $c) = (1, '2', 'three');
252
Assign to the variable x the value "a" if calling the function condition returns true, or the value "b" otherwise.
my $x = condition() ? "a" : "b";
254
Replace all exact occurrences of "foo" with "bar" in the string list x
map { s/^foo$/bar/g } @x;
255
Print the values of the set x to the standard output.
The order of the elements is irrelevant and is not required to remain the same next time.
print "$_\n" for @x;
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
print "$_\n" for reverse (0..5);
257
Print each index i and value x from the list items, from the last down to the first.
for ($i = $#items; $i >= 0; $i--) {
    print "$i $items[$i]\n";
}
258
Convert the string values from list a into a list of integers b.
@b = map { $_ += 0 } @a
259
Build the list parts consisting of substrings of the input string s, separated by any of the characters ',' (comma), '-' (dash), '_' (underscore).
my @parts = split(/[,\-_]/, $s);
260
Declare a new list items of string elements, containing zero elements
my @items;
# or
my @items = ();
266
Assign to the string s the value of the string v repeated n times, and write it out.

E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
my $s = $v x $n;
272
Fizz buzz is a children's counting game, and a trivial programming task used to affirm that a programmer knows the basics of a language: loops, conditions and I/O.

The typical fizz buzz game is to count from 1 to 100, saying each number in turn. When the number is divisible by 3, instead say "Fizz". When the number is divisible by 5, instead say "Buzz". When the number is divisible by both 3 and 5, say "FizzBuzz"
for my $i ( 1 .. 100 ) {
    print $i % 3 ? '':'fizz';
    print $i % 5 ? '':'buzz';
    print $i % 3 && $i % 5 ? $i : '';
    print "\n";
}
273
Set the boolean b to true if the directory at filepath p is empty (i.e. doesn't contain any other files and directories)
opendir(my $dh, $p) || die($!);
my $b = scalar(grep { !/^[\.]{1,2}$/ } readdir($dh)) ? 1 : 0;
closedir($dh);
274
Create the string t from the string s, removing all the spaces, newlines, tabulations, etc.
my $t = $s;
$t =~ s/\s*//g;
277
Remove the element e from the set x.

Explains what happens if e was already absent from x.
@x = grep $e ne $_, @x;
284
Create a new list a (or array, or slice) of size n, where all elements are integers initialized with the value 0.
my @a = (0) x $n;
289
Create the string s by concatenating the strings a and b.
my $s = $a . $b;
294
Given an array a containing the three values 1, 12, 42, print out
"1, 12, 42" with a comma and a space after each integer except the last one.
@a = qw (1 12 42);
print join(", ",@a),"\n";
297
Sort the string list data in a case-insensitive manner.

The sorting must not destroy the original casing of the strings.
@data = sort { lc($a) cmp lc($b) } @data;
298
Create the map y by cloning the map x.

y is a shallow copy, not a deep copy.
my %y = %x;
299
Write a line of comments.

This line will not be compiled or executed.
# This is a comment
302
Give the integer x = 8, assign to the string s the value "Our sun has 8 planets", where the number 8 was evaluated from x.
$s = "Out sun has $x planets"