Remix.run Logo
andrewl-hn 2 days ago

My go-to use case for modern Perl is to be the default program instead of sed. Sed regex support is abysmal and the same command line flags behave differently between BSD (and macOS) and GNU versions, in particular the `-i` for doing replacements - the number one use case for the program. So, this means that many shell one-liners and small scripts don't really work the same way on macOS and on Linux, and it's pretty annoying.

Perl is straight up better. You need to remember one word: pie - for it's command line options, and now you can do:

    ```
    echo "John Doe" > name.txt
    perl -p -i -e 's/(?<first>\w+)\s+(?<last>\w+)/"$+{last}, $+{first}"/e' name.txt
    # name.txt after the command: `Doe, John`
    ```
First of all, it woks the same way across platforms.

Second, you get all sorts of goodies: named capture groups, lookahead and lookbehind matching, unicode, you can write multiline regexes using extended syntax if you do something complicated.

And finally, if your shell script needs some logic: functions, ifs, or loops, Perl is straight up better than Bash. Some of you will say "I'll do it in Python", and I agree. But if your script is mostly calling other tools like git, find, make, etc, then Perl like Bash can just call them in backticks instead of wrapping things into arrays and strings. It just reads better.

BTW Ruby can do it, too, so it's another good option.

nicwolff a day ago | parent [-]

I remember π and e and type

  perl -pi -e '...' file.txt
mpyne a day ago | parent [-]

And if you are using a newer Perl they sometimes add features that aren't enabled by default unless you opt-in with a 'use v5.38' style declaration.

If you want those features on in your one-liner you can use -E instead of -e

    perl -pi -E '...' file.txt
(I used to need this long ago when I wanted to use the then-new "say" in my one-liners)