Perl Advent Calendar 2020 - There is No Try
eval Stinks!
Even if not a huge increase in the code needed for the operation, it's a bunch of magic to remember every time. If you don't do this sort of thing, though, you've got a big opening for horrible error-handling problems.
use Try::Tiny;
my $start = Time::HiRes::time;
return try {
$self->computation_helper->compute_stuff;
} catch {
my $error = $_ eq '' ? 'unknown error' : "$_";
$self->set_last_error( "couldn't get stuff computed: $error" );
return undef;
} finally {
my $failed = @_;
my $end = Time::HiRes::time;
warn sprintf "took %f seconds to %s",
$end - $start,
$failed ? 'fail' : 'succeed';
};Interpolating Functions and Expressions Within Strings - Perl Cookbook [Book]
Interpolating Functions and Expressions Within Strings Problem You want a function call or expression to expand within a string. This lets you construct more complex templates than with simple scalar … - Selection from Perl Cookbook [Book]
Or you can use the slightly sneaky @{[ LIST EXPR ]} or ${ (SCALAR EXPR ) } expansions:
$answer = "STRING @{[ LIST EXPR ]} MORE STRING";
$answer = "STRING ${\( SCALAR EXPR )} MORE STRING";Perl do
Basically after calling do $filename; we need to check both $! and $@ and verify that both are empty as either one of them can contain an error.
Modern Perl CGI | Aristotle [blogs.perl.org]
A modernisation of this using Plack is straightforwardly equivalent:
#!/usr/bin/env perl
use strict;
use warnings;
use Plack::Request;
use Encode::Simple;
use JSON::MaybeXS;
my $app = sub {
my $req = Plack::Request->new($_[0]);
my $input = eval { decode 'UTF-8', $req->parameters->{'input'} };
[ 200, [ 'Content-Type', 'application/json; charset=UTF-8' ], [ encode_json { output => uc $input } ] ];
};
This is now a full PSGI app and as such gains all the same additional deployment options of the Mojolicious example. To deploy it as a CGI script you add this line at the bottom:
use Plack::Handler::CGI; Plack::Handler::CGI->new->run($app);
In all it takes about twice as long to load as the CGI.pm example, compared to the Mojolicious example taking about 7× as long. In exchange you get all the benefits of the PSGI ecosystem – without losing any of the strengths of deploying as a CGI script, unlike the Mojolicious example.
Modern Perl toolchain for Git managed web apps | kappataumu.com
But this also trickles down inside VMs. Working with Linux, i’ve found that keeping the system as pristine as possible after installation is a good thing. When working with Perl, I set the following objectives:
- Leave the system Perl alone.
- Install any Perl I choose.
- And even switch between installed Perls
- Either globally or on a per-project page
- Manage Perl module dependencies within the project’s git repo.
The Wisdom of TAP Numbering in a JavaScript World – Wumpus Cave
Avoiding a test count seems to be the trend in Perl modules these days. After all, automated test libraries in other languages don’t have anything similar, and they seem to get by fine. If the test fails in the middle, that can be detected by a non-zero exit code. It’s always felt like annoying bookkeeping, so why bother?
For simple tests like the above, I think that’s fine. Failing with a non-zero exit code has worked reliably for me in the past.
However, there’s one place where I think TAP had the right idea way back in 1988: event driven or otherwise asynchronous code. Systems like this have been popping up in Perl over the years, but naturally, it’s Node.js that has built an entire ecosystem around the concept. Here’s one of my tests that uses a callback system:
Perl Advent Calendar 2019 - Memories of Past Lives
Persisting between program runs
This is all very well, but Memoize uses an in memory cache. Jolly's problem is that each time he runs his code his program has to re-do all the work up until the point that it crashes. Using memoize like above won't speed up his code at all as every time the script runs it starts with a fresh empty cache.
What we need to do is what the Wise Old Elf suggested - persist our results between program runs.
Well, Memoize can do that:
Perl Advent Calendar 2019 - We Wish You a Meme Christmas
Imager is a handy dandy image drawing library in Perl that we're going to be using for our Meme creation needs.
Imager has about a gazillion methods to do pretty much every standard graphics manipulation you can imagine. But, shockingly, it doesn't have a way to draw standard meme text (Impact font, white text, black outline.) We can fix that by adding our own plugin:
json - "Fatal error: 'EXTERN.h' file not found" while installing Perl modules - Stack Overflow
First, do not use the system Perl on MacOS. The installed version is for Apple, not for you
The best practice seems to be starting with a Perl using brew install perl and work in this environment, remembering to setup your bash_profile as directed by the installer.
Also worth remembering to do a brew link perl. If you receive warnings about this clobbering what looks like system Perl libraries don't worry - these are likely modules that were installed by you over the top and it will cause you less trouble to link over these. If you have concerns, make a note of which module installs will be cleared and re-install them once your environment is configured ( ie your module installer approach is configured using cpanm or sticking with the old perl -MCPAN -e shell etc)
(Other languages like Ruby have the same issue)
A Perl getopts example | alvinalexander.com
Perl getopts FAQ: Can you demonstrate how to use the getopts function? (Also written as, "Can you demonstrate how to read Perl command line arguments?")
App::Stacktrace - Stack trace - metacpan.org
perl-stacktrace prints Perl stack traces of Perl threads for a given Perl process. For each Perl frame, the full file name and line number are printed.
David Golden - "Taking Perl to Eleven with Higher-Order Functions"
# Transformation helper function
sub _x {
my $v = shift;
my $is_code = ref($v) eq 'CODE';
return $is_code ? $v->() : $v; # What about arguments to $v??
}
Data::Fake
Lookahead and Lookbehind Tutorial—Tips &Tricks
Lookarounds often cause confusion to the regex apprentice. I believe this confusion promptly disappears if one simple point is firmly grasped. It is that at the end of a lookahead or a lookbehind, the regex engine hasn't moved on the string. You can chain three more lookaheads after the first, and the regex engine still won't move. In fact, that's a useful technique.
Deploying Perl Apps using Docker, Gitlab & Kubernetes
German Perl Workshop 2019 München 2019-03-06
Thomas Klausner
Moose is Perl: a guide to the new revolution | YouTube
Ricardo Signes at Oscon - July 20-24, 2014
Fork yeah!
Recently at work I had to speed up a Perl script that processed files. Perl can spawn multiple processes with the fork function, but things can go awry unless you manage the subprocesses correctly. I adding forking to the script and was able to improve the script’s throughput rate nearly 10x, but it took me a few attempts to get it right. In this article I’m going to show you how to use fork safely and avoid some common mistakes.
Perl Advent Calendar 2017 - Tiny Path Handling
Path::Tiny is a tiny abstraction around file paths that makes it very easy to manipulate them and perform common operations on them.
Recently I've started using Path::Tiny in preference to both the internal Perl operators for file manipulation and the other abstractions like File::Spec and Path::Class because it makes it really easy to handle common operations easily without making the kind of common mistakes that those other approaches often result in when you're coding quickly.
Perl Advent Calendar 2018 - Christmas Quoting
use B qw(perlstring);
say STDERR 'DEBUG: The next $childname is '. perlstring($childname)
Bless My Referents
Object-oriented programming in Perl is easy. Forget the heavy theory and the sesquipedalian jargon: classes in Perl are just regular packages, objects are just variables, methods are just subroutines. The syntax and semantics are a little different from regular Perl, but the basic building blocks are completely familiar.
Setting up a Perl Development Environment with plenv - xdg.me
This is a slightly modified copy of something I posted internally at work about setting up a development environment using plenv, which keeps your working Perl isolated from your system Perl. Many expert Perl developers already have some variation of this, but I’m posting it as a public service for people who’ve wanted this but never got around to it.
(I used to use perlbrew, but switched to plenv and haven’t looked back).