Substring DWIMmery

TL;DR

I was reminded that substr Does What I Mean.

As already pointed out in Avoid the “butterfly operator” with command-line options , this tweet from Αριστοτέλης Παγκαλτζής was precious for learning new stuff:

tweet screenshot

In addition to option -0xxx, another part struck me, i.e. the removal of the opening and closing square brackets from the encoded string like this:

$str = substr $str, 1, -1;

It just makes sense that -1 can be used in substr to say up to the 1-before-last character of the string, but for some reason this never stuck in my brain and I’m positive that I would have written this in the longer and error prone way:

my $len = length $str;
$str = substr $str, 1, $len - 2;

or in the additionally less readable way:

$str = substr $str, 1, length($str) - 2;

So there you have it: Αριστοτέλης taught me not one but two things with one single tweet.

Selfishly speaking… it’s an excellent reason to write stuff 😄


Comments? Octodon, , GitHub, Reddit, or drop me a line!