SlideShare a Scribd company logo
04/25/17 1
One-linersOne-liners
Perl Brown Bag
Shaun Griffith
April 25, 2017
04/25/17 2
Agenda
• -e is for Execute
• Quoting
• Line endings
• Implied loops
• Regexes
• Line Autosplit
• BEGIN / END
• Sorting
04/25/17 3
-e is for Execute
Recall -e for “execute this code”
> perl -e 'print "one two threen"'
one two three
> perl -e 'print 5+3, "n"'
8
• Any valid code is executed.
• (Other command line arguments may modify or
interfere with your intention though.)
04/25/17 4
Quoting
Use q(), qq() to avoid shell expansion
> perl -e '$x = q(one); print qq(x is $xn);'
x is one
Sometimes you have to escape Perl or Bash
or DOS anyway.
> perl -e '$x = q(one); print qq($x is $xn);'
one is one
> perl -e '$x = q(one); print qq($x is $xn);'
$x is one
• DOS seems to require doublequotes for the -e
argument.
• Some one-liners are nearly impossible in DOS.
• Give up, save the script in a file if it takes too
long.
04/25/17 5
Line Endings
Little L (-l) to fiddle line endings for you
> perl -e 'print qq(one); print qq(two)'
onetwo
> perl -le 'print qq(one); print qq(two)'
one
two
(Works the same on inputs, but you don't
usually care about that.)
04/25/17 6
Implied Loops
If you want to use it as a filter, an implied
loop is ready-made
•-n for “don't print every line”
•-p for “print every line (i.e., $_)”
> ls –1 | perl -nle 'print qq($. $_);'
1: a_file.txt
2: b_file.txt
3: c_file.txt
> ls –1 | perl -ple 'print $.;'
1
a_file.txt
2
b_file.txt
3
c_file.txt
04/25/17 7
Implied Loops (2)
What is it really doing?
•Use the deparser to see:
> perl -MO=Deparse -ple 'print $.;'
BEGIN { $/ = "n"; $ = "n"; } # line endings
LINE: while (<>)) { # implied loop around STDIN
chomp $_;
print $.;
}
continue {
# -p: always print the line (i.e., $_)
print $_;
}
(The output has been cleaned up a bit for clarity.)
04/25/17 8
Regexes
Reverse “word” order?
> ls -1 | perl -ple 's/(w+)(W+)(w+)/$3$2$1/'
txt.a_file
txt.b_file
txt.c_file
Here:
•s/// is replace (substitution)
•w+ is one or more alphanumeric or underline (“word”)
•W+ is one or more non-w (non-”word”)
•() is a capture or group
•$1, $2, $3 are capture groups
• numbered in order (but watch out for nested parens)
04/25/17 9
Line Autosplit
Autosplit lines into tokens
•-a splits on whitespace, into the @F array
• implies -n, if neither -n or -p set
•Or use -F to set delimiter
• implies -a, -n
> ls -1 | perl –F '_' -lane 'print reverse qq(@F)'
file.txt a
file.txt b
file.txt c
• Or access individual elements:
> ls -1 | perl –F '_' -lane 'print $F[0]'
a
b
c
04/25/17 10
BEGIN / END
For actions before or after the implied loop, use
BEGIN{...} or END{...}
•These are special, predefined functions.
•BEGIN is called immediately after it is defined (closing paren).
•END is called just before program exit.
•It doesn't matter where they are defined, they still execute as above.
•Therefore, they are by definition not inside the loop.
•A poor man's line counter, where $. is the current input line
> ls -1 | perl -nle 'END{print qq(lines: $.)}'
lines: 3
• Start a counter from a specific number:
> ls -1 | perl -nle 'BEGIN{$x=17} $x++; END{print $x}'
lines: 20
04/25/17 11
Sorting
To sort an array, use sort
•Default is string sort
•Numeric sort requires code block
> ls -1 | perl -nle 'push @x, $_;END{for my $x (sort @x){print $x}}'
a_file.txt
b_file.txt
c_file.txt
> perl –le '@x=qw(3 2 1); for my $x (sort {$a <=> $b} @x){print $x}}'
1
2
3
04/25/17 12
Sorting (2)
To find unique values, use a hash
•%x is the hash
•$x{key} is the value
•Here's a way to count duplicates, in highest-
count-first order
• Note that $b is first in the sort to get
“reverse order”
• Or you could just use:
• reverse (sort {...})
> perl –le '$x{$_}=1;END{for my $k (sort {$x{$b}<=>$x{$a}} keys %x)
{print qq($k: $x{$k})}}' colours.txt
Blue: 47
Red: 18
Green: 9

More Related Content

PPTX
Python
PDF
Swift the implicit parts
ODP
Very basic functional design patterns
PDF
Advanced perl finer points ,pack&amp;unpack,eval,files
DOCX
lec4.docx
PPTX
Write Your Own Compiler in 24 Hours
PDF
Linux class 15 26 oct 2021
PDF
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Python
Swift the implicit parts
Very basic functional design patterns
Advanced perl finer points ,pack&amp;unpack,eval,files
lec4.docx
Write Your Own Compiler in 24 Hours
Linux class 15 26 oct 2021
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱

What's hot (20)

PPTX
Sharper tools with F#
PPTX
How to tune a query - ODTUG 2012
PDF
The Story About The Migration
 
PDF
Java 8 - project lambda
PPTX
Licão 13 functions
PPTX
Format String
PDF
Data structure doubly linked list programs
PPTX
PL-SQL DIFFERENT PROGRAMS
PPTX
Link list
PDF
Modern Perl for Non-Perl Programmers
PDF
Hello Swift 3/5 - Function
ODP
Functional perl
PDF
The Ring programming language version 1.2 book - Part 10 of 84
PDF
New features in Ruby 2.4
PPTX
Python Programming Essentials - M25 - os and sys modules
PDF
The Ring programming language version 1.2 book - Part 11 of 84
PDF
Everything new with PHP 7.3
PDF
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
PPTX
Pipes and filters
PDF
Do more, faster, by extending WP-CLI
Sharper tools with F#
How to tune a query - ODTUG 2012
The Story About The Migration
 
Java 8 - project lambda
Licão 13 functions
Format String
Data structure doubly linked list programs
PL-SQL DIFFERENT PROGRAMS
Link list
Modern Perl for Non-Perl Programmers
Hello Swift 3/5 - Function
Functional perl
The Ring programming language version 1.2 book - Part 10 of 84
New features in Ruby 2.4
Python Programming Essentials - M25 - os and sys modules
The Ring programming language version 1.2 book - Part 11 of 84
Everything new with PHP 7.3
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Pipes and filters
Do more, faster, by extending WP-CLI
Ad

Similar to Perl one liners (20)

ODP
Perl one-liners
PDF
newperl5
PDF
newperl5
PDF
Introduction to writing readable and maintainable Perl
PDF
Yapc::NA::2009 - Command Line Perl
PPTX
File handle in PROGRAMMable extensible interpreted .pptx
PDF
Scripting and the shell in LINUX
ODP
Perl - laziness, impatience, hubris, and one liners
PPT
Perl Intro 4 Debugger
PPT
Introduction to perl scripting______.ppt
PDF
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
PPT
Perl Basics with Examples
PDF
perltut
PDF
perltut
PPT
Perl Basics for Pentesters Part 1
PPT
Perl Programming_Guide_Document_Refr.ppt
PPT
Perl 101 - The Basics of Perl Programming
PDF
Perl.predefined.variables
PDF
Introduction to PERL Programming - Complete Notes
ODP
Perl In The Command Line
Perl one-liners
newperl5
newperl5
Introduction to writing readable and maintainable Perl
Yapc::NA::2009 - Command Line Perl
File handle in PROGRAMMable extensible interpreted .pptx
Scripting and the shell in LINUX
Perl - laziness, impatience, hubris, and one liners
Perl Intro 4 Debugger
Introduction to perl scripting______.ppt
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Perl Basics with Examples
perltut
perltut
Perl Basics for Pentesters Part 1
Perl Programming_Guide_Document_Refr.ppt
Perl 101 - The Basics of Perl Programming
Perl.predefined.variables
Introduction to PERL Programming - Complete Notes
Perl In The Command Line
Ad

More from Shaun Griffith (7)

PPT
Perl Intro 8 File Handles
PPT
Perl Intro 7 Subroutines
PPT
Perl Intro 5 Regex Matches And Substitutions
PPT
Perl Intro 6 Ftp
PPT
Perl Intro 3 Datalog Parsing
PPT
Perl Intro 2 First Program
PPT
Perl Intro 9 Command Line Arguments
Perl Intro 8 File Handles
Perl Intro 7 Subroutines
Perl Intro 5 Regex Matches And Substitutions
Perl Intro 6 Ftp
Perl Intro 3 Datalog Parsing
Perl Intro 2 First Program
Perl Intro 9 Command Line Arguments

Recently uploaded (20)

PDF
System and Network Administration Chapter 2
PDF
top salesforce developer skills in 2025.pdf
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Essential Infomation Tech presentation.pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Introduction to Artificial Intelligence
PPTX
history of c programming in notes for students .pptx
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
System and Network Administration Chapter 2
top salesforce developer skills in 2025.pdf
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Transform Your Business with a Software ERP System
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Essential Infomation Tech presentation.pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Introduction to Artificial Intelligence
history of c programming in notes for students .pptx
Reimagine Home Health with the Power of Agentic AI​
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems

Perl one liners

  • 1. 04/25/17 1 One-linersOne-liners Perl Brown Bag Shaun Griffith April 25, 2017
  • 2. 04/25/17 2 Agenda • -e is for Execute • Quoting • Line endings • Implied loops • Regexes • Line Autosplit • BEGIN / END • Sorting
  • 3. 04/25/17 3 -e is for Execute Recall -e for “execute this code” > perl -e 'print "one two threen"' one two three > perl -e 'print 5+3, "n"' 8 • Any valid code is executed. • (Other command line arguments may modify or interfere with your intention though.)
  • 4. 04/25/17 4 Quoting Use q(), qq() to avoid shell expansion > perl -e '$x = q(one); print qq(x is $xn);' x is one Sometimes you have to escape Perl or Bash or DOS anyway. > perl -e '$x = q(one); print qq($x is $xn);' one is one > perl -e '$x = q(one); print qq($x is $xn);' $x is one • DOS seems to require doublequotes for the -e argument. • Some one-liners are nearly impossible in DOS. • Give up, save the script in a file if it takes too long.
  • 5. 04/25/17 5 Line Endings Little L (-l) to fiddle line endings for you > perl -e 'print qq(one); print qq(two)' onetwo > perl -le 'print qq(one); print qq(two)' one two (Works the same on inputs, but you don't usually care about that.)
  • 6. 04/25/17 6 Implied Loops If you want to use it as a filter, an implied loop is ready-made •-n for “don't print every line” •-p for “print every line (i.e., $_)” > ls –1 | perl -nle 'print qq($. $_);' 1: a_file.txt 2: b_file.txt 3: c_file.txt > ls –1 | perl -ple 'print $.;' 1 a_file.txt 2 b_file.txt 3 c_file.txt
  • 7. 04/25/17 7 Implied Loops (2) What is it really doing? •Use the deparser to see: > perl -MO=Deparse -ple 'print $.;' BEGIN { $/ = "n"; $ = "n"; } # line endings LINE: while (<>)) { # implied loop around STDIN chomp $_; print $.; } continue { # -p: always print the line (i.e., $_) print $_; } (The output has been cleaned up a bit for clarity.)
  • 8. 04/25/17 8 Regexes Reverse “word” order? > ls -1 | perl -ple 's/(w+)(W+)(w+)/$3$2$1/' txt.a_file txt.b_file txt.c_file Here: •s/// is replace (substitution) •w+ is one or more alphanumeric or underline (“word”) •W+ is one or more non-w (non-”word”) •() is a capture or group •$1, $2, $3 are capture groups • numbered in order (but watch out for nested parens)
  • 9. 04/25/17 9 Line Autosplit Autosplit lines into tokens •-a splits on whitespace, into the @F array • implies -n, if neither -n or -p set •Or use -F to set delimiter • implies -a, -n > ls -1 | perl –F '_' -lane 'print reverse qq(@F)' file.txt a file.txt b file.txt c • Or access individual elements: > ls -1 | perl –F '_' -lane 'print $F[0]' a b c
  • 10. 04/25/17 10 BEGIN / END For actions before or after the implied loop, use BEGIN{...} or END{...} •These are special, predefined functions. •BEGIN is called immediately after it is defined (closing paren). •END is called just before program exit. •It doesn't matter where they are defined, they still execute as above. •Therefore, they are by definition not inside the loop. •A poor man's line counter, where $. is the current input line > ls -1 | perl -nle 'END{print qq(lines: $.)}' lines: 3 • Start a counter from a specific number: > ls -1 | perl -nle 'BEGIN{$x=17} $x++; END{print $x}' lines: 20
  • 11. 04/25/17 11 Sorting To sort an array, use sort •Default is string sort •Numeric sort requires code block > ls -1 | perl -nle 'push @x, $_;END{for my $x (sort @x){print $x}}' a_file.txt b_file.txt c_file.txt > perl –le '@x=qw(3 2 1); for my $x (sort {$a <=> $b} @x){print $x}}' 1 2 3
  • 12. 04/25/17 12 Sorting (2) To find unique values, use a hash •%x is the hash •$x{key} is the value •Here's a way to count duplicates, in highest- count-first order • Note that $b is first in the sort to get “reverse order” • Or you could just use: • reverse (sort {...}) > perl –le '$x{$_}=1;END{for my $k (sort {$x{$b}<=>$x{$a}} keys %x) {print qq($k: $x{$k})}}' colours.txt Blue: 47 Red: 18 Green: 9