Some Perl one-liners

In response to brian d foy's post looking for the best Perl one-liners you've written I dug out my one liners file that I occasionally update.

I wouldn't say that many of these count in the "best" category, some of the tasks can be accomplished with system utilities and some are obfuscated or golfed. But I find it useful to keep these around to remind me of solutions that I might otherwise forget or have to re-invent.

So with those provisos here they are:

# Set an xterm title
perl -e 'print "\c[];@ARGV\a"' Some title here

# dos2unix
perl -i -pe 's/\r//' dos.txt

# Doublespace a file
perl -pe '$_.=$/' file

# Print every line twice
perl -pe '$\=$_' file

# Print last line of a file. tail -1
perl -pe '$*=$_}{$_=$*' file

# wc -l
perl -le 'print $==()=<>' file

# Sum the numbers in the first column of a file (with symmetry)
perl -lpe '$,+=$_}{$_=+$,' file
perl -lpe '${}}+=+${_}}{${_}+=+${}}' file

# Remove the first column of a file
perl -nale 'shift@F;print"@F"'

# Find the version number of a module
perl -le 'eval "require $ARGV[0]" and print $ARGV[0]->VERSION' Some::Module

# tail -5
perl -ne '$i=$.%5; $a[$i]=$_; END{print @a[$i+1..$#a,0..$i]}' file
perl -ne 'END{print@a[$i+1..$#a,0..$i]}$a[$i=$.%5]=$_' file

# Print filename before line
perl -pe '$_="$ARGV: $_"' file

# Print filename and line number before line
perl -ne 'print $ARGV,":", $., ": ", $_; $. = 0 if eof' file file2

# Extract Pod (ignore code)
perl -nle 'print if /^=/ .. /^=cut/' file

# Extract code (ignore Pod)
perl -nle 'print if not /^=/ .. /^=cut/' file

# print a specific line of a file
perl -ne 'print and exit if $. == 3' file
perl -ne 'print and last if $. == 3' file

# grep -v
perl -ne 'print if not /foo/' file
perl -pe 'goto LINE if /foo/' file

# Generate a random string
perl -le 'print map{(a..z)[rand 26]} 0..rand 10'

# Print lines with only one word
perl -nae 'print if @F == 1' file

# Remove repeated lines
perl -i -ne 'print unless $h{$_}++' file

# Remove all occurrence of pattern except for the first one
perl -ne 'print unless /pattern/ and $i++' file

# Generate a list of months (long and short formats)
cal 2009 | perl -lane '@F==3&&print for @F'
cal 2009 | perl -lane '@F==3&&print substr $_, 0, 3 for @F'

# Remove blank lines
perl -ane '@F && print' file

# Add newline to the end of a file
perl -plee file1 file2 ...
perl -pe '$_ .= $/ if eof and not /\n/' file1 file2 ...
perl -i -pl -end file

# Check a file for tabs.
perl -ne 'die "File $ARGV contains tabs\n" if /\t/' file

# Print a match and exit
perl -ne 'print and last if /foo/' file

# Exit after first match
perl -ne 'print; last if /foo/' file

# Exit before first match
perl -pe 'last if /foo/' file
perl -pe 'die $_ if /foo/' file

# Count the vowels in a file
perl -lne 'END{print $c} $c += tr/aeiou//' file

Leave a comment

About John McNamara

user-pic Just another Perl hacker