A whirlwind review of Perl advent calendars for 2018

Overview

There were some other Perl-related advent calendars as well:

Perl Advent Calendar

The Perl 5 Advent Calendar, sometimes managed by Jerrad Pierce, this year run by Mark Fowler.

the Perl Advent Calendar 2018

My highlights

WebPerl

Hauke D is working on a really cool project that lets you use Perl in webpages (as a kind of Javascript replacement). This is done through the magic of WebAssembly and Emscripten.

I had a really cool plan for a demo here, but I couldn't manage to get it compile properly (once I do, if I can make it work, I will update this later).

Perl in the Browser; the WebPerl project

Data::Rmap

A handy module that will recurse through a data structure, and run a code block on it. This (may) simplify handling complex data structures.

Santa’s deepdive in an ocean of stockings; Data::Rmap

Devel::hdb

A web-based debugger for Perl. Because everything is available via REST, you can then interact with the debugger from another program, if you want to try automating debugging?

It isn't perfect: in particular, at least in Safari, it's a bit unsteady with showing you particular variables, and you can't look only at a particular key of a hash.

However, it looks interesting, and the REST/JSON-ability is intriguing.

Debug Hard; Devel::hdb

Quick cool things I want to remember…

B::perlstring

Perl ships with the B module, which interacts with the Perl compiler, and lets you do weird magical things.

One (small) utility is the perlstring() function, which properly escapes a (potentially) weird scalar, without having to interact with Data::Dumper or similar modules.

I don't think I will ever use this, because I pretty much always have Data::Dump available, but it's an interesting tidbit.

Christmas Quoting; B::perlstring

Mu

This is purely a syntactic-sugar module. Here is the core of the source code:

sub import {
    my $caller = caller;
    $_->import::into( $caller ) for qw( Moo MooX::ShortHas );
}

MooX::ShortHas provides shorter versions of the has keyword with the common defaults, so that you don't have to type quite as much boilerplate.

Next time I try to write Moo-style object-oriented code, hopefully I'll remember to try this out.

Mu; Mu (MooX::ShortHas)

App::ccdiff

Mostly, I just wanted to point to this youtube video: Perl Conference in Glasgow talk. It's almost an hour, so we don't have time to watch it here, but it's a fun little talk.

Spot The Difference; App::ccdiff

Hash::Flatten

I'm convinced that I have run into this problem before, and would have used this module. Sadly, I can't remember the details.

It takes a multi-level data structure, and joins up all of the keys until you get a single-level one. It can also unflatten.

Handling complex data structures; Hash::Flatten

Everything

DayTopic
1

Sign o’ The Times; Calendar::List

Generate lists of dates, aimed at things re-occuring weekly.

2

Perl in the Browser; the WebPerl project

Use Perl to do JavaScript-y things!

3

REST API and the Baby; Cpan::JSON::XS::Type

Make sure your data serializes to JSON properly by explicit typing.

4

Christmas Quoting; B::perlstring

A “built-in” way to safely dump a string.

5

Santa’s deepdive in an ocean of stockings; Data::Rmap

Apply map recursively through a data structure.

6

Sticky Delight; Array::Sticky Array::Sticky::INC

Make the heads of arrays “sticky”, even through unshifts.

7

Convert CSV to Pivot Table; Text::CSV::Pivot

Pivot your CSV files.

8

DBD::mysql versus DBD::MariaDB; DBD::MariaDB

When to use DBD::MariaDB instead of DBD::mysql.

9

The Fix Is In; App::sigfix

CLI program to transform modern function signatures into the older style.

10

Christmas Tree Babbles; Babble

A Perl transpiler, similar to the Javascript Babel tool. Still experimental.

11

Mu; Mu (MooX::ShortHas)

Syntactic sugar to reduce the overhead of declaring Moo-based classes.

12

Growing Christmas Trees; SVG SVG::ChristmasTree

Use the SVG module to create a module to create a Christmas tree image.

13

Lost in legacy arguments; Sub::Params

Let functions support either positional or named parameters at the same time.

14

The future is now; Future

Asynchronous code, using Future.

15

Spot The Difference; App::ccdiff

Do character-by-character diffs.

16

Handling complex data structures; Hash::Flatten

Flatten nested data structures to one level.

17

Christmas Tunes!; OAuth::CmdLine::Spotify

Allow CLI programs to authenticate against Spotify.

18

Test/Compare Your Excel; Test::Excel

Determine if two Excel workbooks are the same.

19

Cute Christmas Animals; Mojo::Promise

Web programming with Promises, instead of Futures

20

Christmas-iSH; iSH home page

A crazy system that, mostly, lets you run linux on your iPhone. (In a userland i386 emulator…)

21

Debug Hard; Devel::hdb

A debugger, with an HTTP/REST front end.

22

Validation; Method::ParamValidator

A module that can be used to ensure that method parameters are valid.

23

Legacy code strikes again; Context::Singleton

A module that provides (I think) something similar to local variables, with more control, ways to handle default values, etc.

24

Watching the Perl Conference Again; App::HTTPThis App::HTTPSThis

CLI programs to serve directories via HTTP and HTTPS.

25

Merry Christmas

A summary of contributors and links to other advent calendars.

Perl 6 Advent Calendar

The Perl 6 Advent Calendar 2018

My highlights

Porting a program

A nice recapitulation of porting a program from Perl 5 to Perl 6.

Porting Vigilance, integrating Perl 6 with standard tools

Perl6 in browser

This day (7) in the calendar is ostensibly about Cellular Automata. Cool as cellular automata are, though, I think the really interesting thing here is 6pad.

Play with it here.

It's a bit slow, and still in development, but it works.

Some other work in this area includes rakudo.js (see also here), and Webperl (from above) also includes some Perl 6 support (by incorporating Rakudo.js).

Automatic on a Cellular Level

jmp

If you do a lot of programming in the terminal, the jmp program might be interesting? It's a front-end to things like grep, ack, etc., that will then jump directly into your editor. It can also parse things like error messages, test errors, etc.

jmp-starting your work flow

Fancy comments

Perl 6 adds "declarator blocks" to POD declarator blocks.

The MAIN subroutine uses these comments when it auto-generates the usage message, so you can slightly customize the help message in this way.

There is also discussion of using multi-method MAIN to handle various options, the hidden-from-USAGE trait, and the %*SUB-MAIN-OPTS variable.

Checking Your List Twice

Everything

DayTopic
1

Porting Vigilance, integrating Perl 6 with standard tools

Porting a script from Perl 5 to Perl 6

2

Like Perls in a Pod: document everything (and test the documentation)

Discusses Perl 6 POD, and some of the programmatic ways to access it.

3

jmp 2 it

jmp is a CLI program that helps you move from grep/awk/ack/etc. directly to your editor.

4

New Perl 6 POD Features for the New Year

Doesn't actually have much to do with POD 6 features; this is a discussion of some of the issues run into while trying to implement some missing POD 6 features.

5

Variables

A discussion of some interesting things about variables.

6

Lazy and Industrious Elves; Object::Delayed

A module that introduces the slack and catchup subs; these can be used to either delay some code execution until it is actually needed, or perform some tasks asynchronously.

7

Automatic on a Cellular Level

Creating one-dimensional cellular automata in Perl 6. It rather buries the lede though, which is 6pad — Perl 6 in your* browser. (*: not all browsers work)

8

Make your Perl 6 grammar compact

Suggestions for cleaning up grammars, primarily by using multi-methods, multi-tokens, and multi-rules.

9

Let’s get astroPhysical! – Constants in Perl 6

The author of Perl 5 Astro::Constants discusses porting to Perl 6, and how to define a constant in Perl 6.

10

jmp-starting your work flow

An update to the jmp program from day 3.

11

Testing your Times Tables with Perl 6

A simple Perl 6 program that tests you on your times tables.

12

Building a flexible grammar

Mrs. Claus runs into l10n issues, and refactors a grammar to move some logic outside of it.

13

Web server from scratch with Cro and Debian; cro

A quick introduction to installing Perl 6 and cro on Debian. cro is an asynchronous web services framework for Perl 6.

14

Designing a (little) Spacecraft with Perl 6

Because LDAP (although not yet), the author starts describing how you can take an ASN.1 specification, and turn it into Perl 6.

15

Building a (little) Spacecraft with Perl 6

Continuing the adventures from yesterday, a description of how some of the roles and multi-methods are set up to handle serializing and de-serializing ASN.1 objects.

16

Checking Your List Twice

A discussion of how to use special comments, traits, and multi-methods to make auto-generated usage instructions more powerful.

17

Compiling our way to happiness

A descent into possible hypothetical languages or programming paradigms the author would like Perl 6 to support, in order to solve the famed SEND + MORE = MONEY equation.

18

An SVG Christmas Tree; SVG

Only a few days after the Perl 5 Advent Calendar, the Perl 6 Advent Calendar tackles creating christmas trees in SVG. Frankly, the Perl 5 one is better, and someone needs to work on the Perl 6 SVG module.

19

Interactive Desktop Apps; GTK::Simple

Creating a simple GUI app in Perl 6, using the GTK toolkit.

20

Propositional combinatorics in Perl 6

A mathematician shows how to use Perl 6 to study something in n-dimensional space, but what exactly I'm not sure. This is all disguised as a discussion about how North Pole elves are conversant with 6d presents, which apparently make children happier than ones they can hold in their 3d hands?

21

A Red Secret Santa; RED

A Perl 6 ORM, although still in development. Possibly not working (according to the Wiki).

22

Testing Cro HTTP APIs

Jonathan Worthington, creator of Cro, and large parts of the current Perl 6 stack, discusses how to test Cro route handlers.

23

Blin, it’s Christmas soon!

The Perl 6 IRC channel has a number of bots (is 17 large?) which do nice things like automate git bisect testing. Blin is a new bot that uses git bisect to find out what commit caused a module to stop working.

24

Topic Modeling with Perl 6

This is about … topic modeling ? … using a module to do “Latent Dirichlet Allocation” ? I think? What is interesting to me are the examples of fetching data with the WWW module and friends.

25

Calling numbers names

Some interesting snippets of Perl 6 code that lets you test numbers for amicability, happiness, and two other qualities.

Perl 6 One-liner Advent Calendar

Andrew Shitov’s advent calendar looking at Perl 6 one-liners.

The Perl 6 One-liner Advent Calendar 2018

My highlights

Project Euler problem 19

Another solution to Project Euler problem 19

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

From day 13:

say ( Date.new(year => 1901) ..^ Date.new(year => 2001) ).grep({.day == 1 && .day-of-week == 7}).elems

And from the comments of day 13:

say +(Date.new(1901,1,1)..^Date.new(2001,1,1)).grep: {.day == 1 && .day-of-week == 7}

Then, on day 14, instead of scanning all dates, just scan the first of the months for Sundays:

(gather for 1901..2000 X 1..12 { take Date.new(|@_, 1) }).grep(*.day-of-week == 7).elems.say;

However, he was getting excited about gather/take, and someone noted that map would work as well:

say +(1901..2000 X 1..12).map( {Date.new(|@_, 1)} ).grep(*.day-of-week == 7);

Calculating π

Computing the value of π

Based on the formula:

π=4n=0-1n2n+1

we can calculate π with:

say 4 * [+] (^1000).map({(-1) ** $_ / (2 * $_ + 1)})

But, you can also create it using the sequence operator:

say 4 * [+] <1/1>, {-Rat.new($^n.numerator, $^n.denominator + 2)} ... *.abs < 1E-5;

Finally, in the comments, Damian Conway offers:

say 4 * [+] (1, -1, 1 … *) «/« (1, 3, 5 … 9999);

( although he prefers it across two lines, because it looks more like the Leibnitz series:

say 4 * [+] (1, -1, 1 … * ) «/« (1, 3, 5 … 9999);

)

Everything

DayTopic
1

Generating random passwords

('0'..'z').pick(15).join.say
2

Grepping dividable numbers (Project Euler problem 1)

say sum((1..999).grep: * %% (3 | 5))
3

Generating random integers

2019.rand.Int.say
4

Working with big numbers (Project Euler problem 13)

< 37107287433902102798797998220837590246510135740250 # Other 98 numbers here 53503534526472524250874054075591789781264330331690 >.sum.substr(0, 10).say
5

What’s the date today

DateTime.now.yyyy-mm-dd.say DateTime.now(formatter => -> $dt { sprintf '%02d.%02d.%04d', $dt.day, $dt.month, $dt.year }).say
6

Testing palindromic numbers (Project Euler problem 4)

(((999...100) X* (999...100)).grep: {$^a eq $^a.flip}).max.say (((999...100) X* (999...100)).grep: {$^a eq $^a.flip}).head(10).max.say
7

The joy of Unicode

say π × $𝜌² say pi * $r ** 2

And another option for day 2:

sub f($n) { ($n «×» (1…1000 / $n)).grep: * < 1000 } say (f(3) ∪ f(5)).keys.sum;
8

Adding up even Fibonacci numbers (Project Euler problem 2)

(1, 1, * + * ... * > 4_000_000).grep(* %% 2).sum.say
9

More on X, .., and

1..10 X* 1..10
10

Reduction operator

Factorial:

say [*] 1..2019

Project Euler problem 5:

say [lcm] 1..20

Rotating a matrix:

[Z] <A B C>, <D E F>, <H I J>
11

Solving problem 34 (Project Euler problem 34)

say [+] (3..50_000).grep({$_ == [+] .comb.map({[*] 2..$_})})
12

What’s behind 0.1 + 0.2

say 0.1 + 0.2 - 0.3 say <1/10> + <2/10> - <3/10>
13

How many days in the century match a condition (Project Euler problem 19)

say ( Date.new(year => 1901) ..^ Date.new(year => 2001) ).grep({.day == 1 && .day-of-week == 7}).elems
14

Another solution to yesterday’s problem (Project Euler problem 19)

(gather for 1901..2000 X 1..12 { take Date.new(|@_, 1) }).grep(*.day-of-week == 7).elems.say;

An update based on reader comments:

say +(1901..2000 X 1..12).map( {Date.new(|@_, 1)} ).grep(*.day-of-week == 7);
15

Playing with Fibonacci numbers (Project Euler problem 25; Code golf task)

Creating a Fibonacci sequence:

0, 1, * + * ... *

Project Euler problem 25: index of the first Fibonacci number > 1000 digits:

say (0, 1, * + * ... *).first(*.chars >= 1000, :k)

Code golf to print the first 30 Fibonacci characters:

.say for (0, 1, * + * ... *)[^31] .say for (0,1,*+*...*)[^31] (0,1,*+*...*)[^31]>>.say (0,1,*+*…*)[^31]».say (0,1,*+*…*>514229)».say (0,1,*+*…*>7⁷)».say (0,1,*+*…*>𐧴)».say

In that last one, the missing character is U+109F4, “meroitic cursive number eight hundred thousand”, of which the only image seems to be in the Unicode Standard PDFs.

16

Distance between two points

say abs(5.5+2i - (1.5+5i)) say sqrt((5.5 - 1.5)² + (2 - 5)²)
17

Playing with prime numbers (Project Euler problem 7; code golf)

Project Euler problem 7; print the 10001st prime number:

say ((1..*).grep: *.is-prime)[10000]

Code golf: print prime numbers below 100:

.is-prime&&.say for ^Ⅽ

The “Ⅽ” character is U+216D, “roman numeral one hundred”.

(which, in un-optimized form is:)

.say if .is-prime for ^100
18

Renaming files

@*ARGS[0..*-2].sort.map: *.Str.IO.rename(++@*ARGS[*-1])
19

Computing the value of π

say 4 * [+] (^1000).map({(-1) ** $_ / (2 * $_ + 1)})

or

say 4 * [+] <1/1>, {-Rat.new($^n.numerator, $^n.denominator + 2)} ... *.abs < 1E-5;

or, from the comments:

say 4 * [+] (1, -1, 1 … *) «/« (1, 3, 5 … 9999);
20

Command-line options

A review of the perl6 command line options: -e, -n, and -p

21

Merging files horizontally

.trim.say for [Z~] @*ARGS.map: *.IO.lines.map: *~ ' '
22

Reversing a file

.say for $*IN.lines.reverse .say for lines.reverse .say for @*ARGS[0].IO.open.lines.reverse @*ARGS[0].IO.open(chomp => False).lines.reverse.put @*ARGS[0].IO.open( nl-in => "\r", chomp => False ).lines.reverse.put
23

Calculating totals

put [Z+] lines.map: *.words
24

Reading files with $*ARGFILES

.say for $*ARGFILES.lines

(The behaviour of the special variable will be changing, subtly, in 6.d.)

25

Tips and ideas for Perl 6 Golf

  • Omit topic variable
  • Use ranges in place of loops
  • Ranges (..) vs sequences ()
  • Use map instead of a loop
  • Omit parentheses
  • Use chained comparisons
  • Choose methods vs functions as appropriate
  • Use Unicode
  • Use superscripts for powers
  • Sigilless variables
  • Default parameters
  • Use && instead of if
  • Choose put vs say
(26)

Overview of the Perl 6 One-liner Advent Calendar 2018

Questions?

Fin