perl.gg

The Maori Farewell: A Clever Perl One-Liner Trick

The "Maori Farewell" is a clever Perl one-liner technique that allows code execution at the start of a script. Named playfully after the Maori people of New Zealand, it exploits the -M command-line option to inject code before the main processing begins. This trick enables Perl programmers to perform initializations or setups in compact one-liners, adding flexibility to command-line scripts without requiring full script files. It's particularly useful when combined with -n or -p switches, enhancing Perl's ability to create powerful, concise command-line tools.

Let's dive in and uncover the magic behind this esoteric Perl feature.

Understanding the Maori Farewell

The Maori Farewell is a clever way to create a pseudo-BEGIN block in Perl one-liners. It takes advantage of the -M command-line option, which is typically used for loading modules. Here's the basic syntax:

At first glance, this might look like we're loading a module named "5," but that's not what's happening. The semicolon after the 5 is the key to this trick. It separates the version number from the code we want to execute.

How It Works

When Perl encounters -M5;, it interprets this as:

  1. Use version 5 of Perl (which is essentially a no-op for modern Perl versions)

  2. Execute any code that follows the semicolon before the main program runs

This behavior allows us to inject code at the beginning of our one-liner, similar to what a BEGIN block would do in a full Perl script.

Practical Examples

Let's explore some practical uses of the Maori Farewell:

Printing a timestamp before processing:

Example output:

This one-liner prints the current timestamp before searching for lines containing "error" (case-insensitive) in logfile.txt.

Setting a custom input record separator:

Example output:

Here, we use the Maori Farewell to set the input record separator to two newlines, effectively making Perl read the file in paragraph mode. It then prints paragraphs longer than 100 characters.

Variations and Limitations

While "5" is commonly used, you can actually use any Perl version number. For instance, -M5.010; would enable Perl 5.10 features like say and state.

It's worth noting that the Maori Farewell doesn't work with the = syntax for importing specific functions from modules. For example, this won't work:

Conclusion

The Maori Farewell is a testament to Perl's flexibility and the creativity of its community. While it might not be something you'll use every day, understanding this trick can come in handy when crafting complex one-liners. It's a powerful tool in the Perl programmer's toolkit, allowing for more sophisticated preprocessing in compact, command-line Perl scripts.

Remember, with great power comes great responsibility. Use the Maori Farewell wisely, and may your Perl one-liners be ever concise and effective!