Friday, July 25, 2008

More Perl One-Liners for Linux Or Unix

Hey There,

Almost time for the weekend, so I thought we'd go back and look at some more simple Perl one-liners. Note that this post is not really meant to be educational in any way, but maybe it'll help someone out there somewhere. If anything, it should pass a good 5 to 10 minutes of your time when you could be doing something useful ;)

Next week, we'll take a look at some very useful Perl one-liners, but for today, we'll keep it light. No sense starting into the weekend with a sense of gloom and doom :) We'll also get back to an example of code porting we put up last week, which caused a deluge of "better" versions of my lame C code. I make no bones about it. It's a weak language for me, and the point of that original post was the "porting" part, which is why the code that got ported from C to Perl and shell was just as imperfect as the original C code. It was ported as thoroughly as possible, which meant keeping the good "and" the bad stuff from the original. Even so, I appreciate all of the helpful suggestions I've received and (I should be able to find time to go through them all this weekend) I'll definitely be putting those better examples of the original code up as soon as I can!

Until then, enjoy,

These first two don't really do much. I just wrote them down while I was trying to jump-start my head :)

Core Belief Shatterer:

perl -e 'if ( `true` == `false` ) {print "I have no idea what to believe anymore\n";}'

Yet another seeming proof of the opposite of a widely-held belief:

perl -e '$wrong=1;$right=2;'

rot13:

perl -pe "tr/A-Za-z/N-ZA-Mn-za-m/" FileToRot

rot13 reversal:

perl -pe "tr/N-ZA-Mn-za-m/A-Za-z/" Rotten_File

rot24 (why not?):

perl -pe "tr/A-Za-z/Y-ZA-Xy-za-x/" FileToRot

rot24 reversal:

perl -pe "tr/Y-ZA-Xy-za-x/A-Za-z/" Rotten_File

Another palindrome finder (no spaces, like "able was I ere I saw Elba"):

perl -lne 'map { print if $_ eq reverse } split' FILE

This one should find palindromes with spaces and ignore case:

host # perl -lne '{ $_ = lc; $_ =~ s/\W//g; $_ eq reverse;print if $_ eq reverse }' FILE

A simple calculator for as many numbers as your command line can handle (substitute -, /, *, etc for other arithmetic equations):

perl -e 'print eval join("+", @ARGV)' NUM1 NUM2 NUM3 NUM4 NUMn...

Two different ways to remove spaces and tabs from the beginning and end of lines (Both the same, just depends on whether you prefer special characters or POSIX style):

perl -ple 's/^\s+//, s/\s+$//' FILENAME

perl -pe 's/^[[:blank:]]+//, s/[[:blank:]]+$//' FILENAME

, Mike