---- Perl One-Liners ----

Perl one-liners examples

Before delving into more complex Perl code, a few short examples are shown to demonstrate the general use of Perl from the command line. For Perl novices it is advisable to take a look at the Introduction page first for a quick overview of Perl basics.
  1. Issue a Perl statement, in this case a greeting message following by a newline, through the -e flag:
    perl -e 'print "hello world\n"'
    
  2. Let Perl add automatically a newline to the output:
    perl -l -e 'print 2**13'
    
  3. Read input from a file and report number of lines and characters:
    perl -lne '$i++; $in += length($_); END { print "$i lines, $in characters"; }' input.txt
    

    try it out with an example input file
  4. Add word count to the output:
    perl -lne '$i++; $in += length($_); $w += scalar split /\s+/, $_; END { print "$i lines, $w words, $in characters"; }' input.txt
    
  5. Redirect output into a file, in this case 100 random numbers between zero and one:
    perl -le 'foreach (1..100) { print rand;}' > random_numbers.txt
    
  6. Carry out modifications within one or more files, e.g. by removing all lines starting with a comment (indicated by a hash symbol), but creating a backup file with suffix '.bak' first.
    perl -p -i.bak -e 's/^#.+//s;' input1.txt input2.txt input3.txt