Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Perl One Liners

ynonperek
November 01, 2011
590

Perl One Liners

Useful perl one liners explained

ynonperek

November 01, 2011
Tweet

Transcript

  1. One Theory perl -e ‘...’ - run a one liner

    with no input perl -ne ‘...’ - run a one liner on every input line perl -pe ‘...’ - same as -ne, AND print each line perl -i files -e ‘...’ - edit files in place Note the quotes. A single quote prevents the shell from grabbing our program Tuesday, November 1, 2011
  2. Print contents of standard input Print readme.txt: perl -pe 1

    readme.txt Create a file named outfile perl -pe 1 > outfile Discussion Tuesday, November 1, 2011
  3. Discussion Conditional printing of file contents selected lines only: print

    if 15..17 matched text only: print if /foo/ combined: print if /begin/.../end/ Tuesday, November 1, 2011
  4. Discussion use -l if line-end char is an issue perl

    -nle ‘print if $_ eq reverse’ /usr/share/dict/words Tuesday, November 1, 2011
  5. Discussion Reverse order of lines This words because reverse imposes

    list context on the <> operator Can also reverse each line using perl -nle ‘print scalar reverse $_’ Tuesday, November 1, 2011
  6. Discussion Print input lines numbered $. is a special perl

    variable holding current line number Can use to print only even/odd lines: perl -ne ‘print if $. % 2 == 0’ Can use to print only non-blank lines: perl -ne 'print ++$n . " $_" if /./;' Count number of lines in a file perl -ne 'END {print $.}' Tuesday, November 1, 2011
  7. Discussion END allows running code when input ends Can use

    perl variables Note the -l for line ending magic Tuesday, November 1, 2011
  8. Discussion Print n lines from the end of input (like

    tail) Use a buffer to remember Note the context: @a = <>; Tuesday, November 1, 2011
  9. perl -p -i.bak -e 's/\bfoo\b/bar/g' *.c Original file (unmodified) will

    be saved as a .bak For example, a.c is backed up as a.c.bak Tuesday, November 1, 2011
  10. In Place Editing Use -i for in place editing Use

    regular expressions for search & replace Can also use: perl -i.old -ne 'print unless 1 .. 10' foo.txt perl -i’*.bak’ -pe 's/(\d+)/ 1 + $1 /ge' file1 file2 Tuesday, November 1, 2011
  11. Discussion Simple file operations modules Get a list of all

    core modules installed with your perl using perldoc perlmodlib Get a list of search paths for modules using perl -e ‘perl -e '$,="\n"; print @INC' Tuesday, November 1, 2011
  12. Discussion Facebook::Graph can access all data stored on facebook in

    a perlish way Use Data::Dumper to print the result Install with cpanm Facebook::Graph Tuesday, November 1, 2011
  13. Discussion Dancer is a mini framework for writing web applications

    The above starts a debug server, serving all files in current path on port 3000 Install with cpanm Dancer Tuesday, November 1, 2011