Perl FAQ 3.13: Can I write useful perl programs on the command line?

Perl FAQ 3.13

Can I write useful perl programs on the command line?

Sure, if they're simple enough. Of course, for most programs, you'll enter them in a file and call perl on them from your shell. That way you can go into the hack/execute/debug cycle. But there are plenty of useful one-liner: see below. (Things marked perl5 need to be run from v5.000 or better, but the rest don't care.)

# what's octal value of random char (":" in this case)?
perl -e 'printf "%#o\n", ord(shift)' ":"

# sum first and last fields
perl -lane 'print $F[0] + $F[1]'

# strip high bits
perl -pe 'tr/\200-\377/\000-\177/'

# find text files
perl -le 'for(@ARGV) {print if -f && -T}' *

# trim newsrc
perl5 -i.old -pe 's/!.*?(\d+)$/! 1-$1/' ~/.newsrc

# cat a dbmfile
perl -e 'dbmopen(%f,shift,undef);while(($k,$v)=each%f){print "$k:\
	$v\n"}' /etc/aliases 

# remove comments from C program
perl5 -0777 -pe 's{/\*.*?\*/}{}gs' foo.c

# make file a month younger than today, defeating reaper daemons
perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *

# find first unused uid
perl5 -le '$i++ while getpwuid($i); print $i'

# find first unused uid after 100, even with perl4
perl -le '$i = 100; $i++ while ($x) = getpwuid($i); print $i'

# detect pathetically insecurable systems
perl5 -le 'use POSIX; print "INSECURE" unless sysconf(_PC_CHOWN_RESTRICTED)'

# display reasonable manpath
echo $PATH | perl5 -nl -072 -e '
    s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'

Ok, the last one was actually an obfuscate perl entry. :-)


Other resources at this site: