SlideShare a Scribd company logo
Perl's Functional Functions
The common (core) ones...
● Built-in:
– grep – Filters a list.
– map – Creates or transforms a list.
– sort – Sorts a list.
● List::Util (core)
– first – Like grep, but returns first one found.
– reduce – Summarizes a list.
The common CPAN ones:
● List::MoreUtils
– any – Return true if any element in list matches.
– all – Return true if all elements match.
– pairwise – Transform two lists, pairwise, into one.
– Many others!
Filtering a list
my @odds;
foreach ( qw( a b c d e ) ) {
push @filtered, $_
if ord( $_ ) % 2;
}
say for @odds;
Filtering a list with grep
my @odds;
foreach (
qw( a b c d e )
) {
push @odds, $_
if ord( $_ ) % 2;
}
say for @odds;
my @odds = grep {
ord( $_ ) % 2
} qw( a b c d e );
say for @odds;
my @odds = grep { ord($_) % 2 } qw( a b c d e );
Which indices contain odd ords?
my @chars = qw( a c f b q r n b d );
my @odds_by_idx = grep {
ord( $chars[$_] ) % 2
} 0 .. $#chars;
grep
● list_b = grep { code block } ( list_a )
● Inside code block, $_ is it.
● If code block's return value is true, $_ is appended to
list_b.
● As with foreach, $_ is an alias.
● list_b and list_a need not be arrays.
● Simple expressions may be used in place of code
block.
Simple expressions in place of code
block
@explosions = grep { /bkaboomb/i } @phrases;
@explosions = grep /bkaboomb/i, @phrases;
@ones = grep { $_ == 1 } @booleans;
@ones = grep $_ == 1, @booleans;
● If it can't be expressed as a simple expression,
use a code block.
● Expression form requires a comma.
Transforming a list
sub chars_to_ords {
my @ords;
foreach ( @_ ) {
push @ords, ord $_;
}
return @ords;
}
my @ord_vals = chars_to_ords( qw( a b c d e ) );
Transforming a list with map
sub chars_to_ords {
my @ords;
foreach ( @_ ) {
push @ords, ord $_;
}
return @ords;
}
my @ordinals
= chars_to_ords(
qw( a b c d e )
);
my @ordinals
= map { ord $_ }
qw( a b c d e );
my @ordinals = map { ord $_ } qw( a b c d e );
Lists don't have to be arrays
say for map { ord } qw( a b c d e );
map
● list_b = map { code block } ( list_a )
● Inside code block, $_ is it.
● code block's return value is appended to list_b.
● As with foreach, $_ is an alias.
● list_b and list_a need not be arrays.
● code block is a subroutine; no last, no next.
● Skip current iteration by returning an empty list.
Simple expressions don't require
code blocks.
say for map ord, qw( a b c d e );
# The expression form requires a comma.
Chaining is legal (even encouraged)
say for
map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [ $_, ord fc $_ ] }
qw( a b c d e );
# The Schwartzian Transform.
Sort?
@sorted = sort @unsorted;
@sorted = sort { $a <=> $b } @unsorted; # Ascend, numeric
@sorted = sort { $b <=> $a } @unsorted; # Descend, numeric
@sorted = sort { $a cmp $b } @unsorted; # Ascend, stringy
@sorted = sort {
$a <=> $b || $a cmp $b
} @unsorted; # Ascending numeric, then stringy.
@sorted
= sort { $a->{name} cmp $b->{name} } @unsorted;
List::Util
$first_one = first { /^kaboomb/i } @haystack;
$sum = reduce { $a + $b } @numbers;
$max = reduce { $a > $b ? $a : $b } @numbers;
List::MoreUtils
$has_quiche = any { /bquicheb/ } @foods; # T/F
$all_unicorns
= all { $_ eq 'unicorn' } @animals; # T/F
@joint_incomes = pairwise { $a + $b } @his, @hers;
@evens_odds = part { $_ % 2 } 1 .. 9; # LOLs
List::MoreUtils “natatime”
my @alphabet = ( 'a' .. 'z' );
my $iterator = natatime 3, @alphabet;
while( my @chars = $iterator->() ) {
print “@charsn”;
}
__END__
a b c
d e f
…
y z
List::MoreUtils
● Too many to mention them all.
– See https://metacpan.org/module/List::MoreUtils
Resources
● perldoc -f grep
● perldoc -f map
● perldoc -f sort
● perldoc List::Util
● https://metacpan.org/module/List::MoreUtils
Salt Lake Perl Mongers
http://saltlake.pm.org
Slides on slideshare.net
http://www.slideshare.net/daoswald/perls-functional-functions
Dave Oswald
davido@cpan.org

More Related Content

What's hot (14)

PPT
Php String And Regular Expressions
mussawir20
 
PPTX
Perl names values and variables
sana mateen
 
PDF
PHP 101
Muhammad Hijazi
 
PPTX
Pig statements
Ganesh Sanap
 
PPTX
Strings,patterns and regular expressions in perl
sana mateen
 
PDF
Regular expression in javascript
Toan Nguyen
 
PDF
Merging tables using R
Rupak Roy
 
PPTX
Power shell basics day 5
Ashish Raj
 
PDF
How to write code you won't hate tomorrow
Pete McFarlane
 
PPTX
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
PDF
Perl6 signatures
Simon Proctor
 
PPTX
Strings and pointers
Gurpreet Singh Sond
 
PPTX
Introduction in php part 2
Bozhidar Boshnakov
 
Php String And Regular Expressions
mussawir20
 
Perl names values and variables
sana mateen
 
PHP 101
Muhammad Hijazi
 
Pig statements
Ganesh Sanap
 
Strings,patterns and regular expressions in perl
sana mateen
 
Regular expression in javascript
Toan Nguyen
 
Merging tables using R
Rupak Roy
 
Power shell basics day 5
Ashish Raj
 
How to write code you won't hate tomorrow
Pete McFarlane
 
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
Perl6 signatures
Simon Proctor
 
Strings and pointers
Gurpreet Singh Sond
 
Introduction in php part 2
Bozhidar Boshnakov
 

Similar to Perls Functional functions (20)

PDF
Wheels we didn't re-invent: Perl's Utility Modules
Workhorse Computing
 
KEY
Introduction to Perl Best Practices
José Castro
 
ODP
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
 
ODP
Map grep sort
Daina Pettit
 
ODP
Functional perl
Errorific
 
PDF
Learning Perl 6 (NPW 2007)
brian d foy
 
PDF
newperl5
tutorialsruby
 
PDF
newperl5
tutorialsruby
 
PDF
Introduction to writing readable and maintainable Perl
Alex Balhatchet
 
ODP
Introduction to Perl
Dave Cross
 
PDF
Scripting3
Nao Dara
 
PDF
Learning Perl 6
brian d foy
 
PPTX
Don’t Fear map & grep: List processing for fun and profit
Mark Gardner
 
PPTX
Unit 1-array,lists and hashes
sana mateen
 
PDF
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
PPT
PERL.ppt
Farmood Alam
 
ODP
Introduction to Perl - Day 1
Dave Cross
 
ODP
Introduction to Perl - Day 2
Dave Cross
 
ODP
Perl Introduction
Marcos Rebelo
 
Wheels we didn't re-invent: Perl's Utility Modules
Workhorse Computing
 
Introduction to Perl Best Practices
José Castro
 
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
 
Map grep sort
Daina Pettit
 
Functional perl
Errorific
 
Learning Perl 6 (NPW 2007)
brian d foy
 
newperl5
tutorialsruby
 
newperl5
tutorialsruby
 
Introduction to writing readable and maintainable Perl
Alex Balhatchet
 
Introduction to Perl
Dave Cross
 
Scripting3
Nao Dara
 
Learning Perl 6
brian d foy
 
Don’t Fear map & grep: List processing for fun and profit
Mark Gardner
 
Unit 1-array,lists and hashes
sana mateen
 
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
PERL.ppt
Farmood Alam
 
Introduction to Perl - Day 1
Dave Cross
 
Introduction to Perl - Day 2
Dave Cross
 
Perl Introduction
Marcos Rebelo
 
Ad

More from daoswald (10)

PDF
Perl: Setting Up An Internal Darkpan
daoswald
 
ODP
Speaking at Tech Events
daoswald
 
ODP
Perl one-liners
daoswald
 
ODP
Whatsnew in-perl
daoswald
 
ODP
Add Perl to Your Toolbelt
daoswald
 
ODP
Think Like a Programmer
daoswald
 
ODP
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
daoswald
 
ODP
Getting started with Perl XS and Inline::C
daoswald
 
ODP
30 Minutes To CPAN
daoswald
 
ODP
Deploying Perl apps on dotCloud
daoswald
 
Perl: Setting Up An Internal Darkpan
daoswald
 
Speaking at Tech Events
daoswald
 
Perl one-liners
daoswald
 
Whatsnew in-perl
daoswald
 
Add Perl to Your Toolbelt
daoswald
 
Think Like a Programmer
daoswald
 
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
daoswald
 
Getting started with Perl XS and Inline::C
daoswald
 
30 Minutes To CPAN
daoswald
 
Deploying Perl apps on dotCloud
daoswald
 
Ad

Recently uploaded (20)

PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 

Perls Functional functions

  • 2. The common (core) ones... ● Built-in: – grep – Filters a list. – map – Creates or transforms a list. – sort – Sorts a list. ● List::Util (core) – first – Like grep, but returns first one found. – reduce – Summarizes a list.
  • 3. The common CPAN ones: ● List::MoreUtils – any – Return true if any element in list matches. – all – Return true if all elements match. – pairwise – Transform two lists, pairwise, into one. – Many others!
  • 4. Filtering a list my @odds; foreach ( qw( a b c d e ) ) { push @filtered, $_ if ord( $_ ) % 2; } say for @odds;
  • 5. Filtering a list with grep my @odds; foreach ( qw( a b c d e ) ) { push @odds, $_ if ord( $_ ) % 2; } say for @odds; my @odds = grep { ord( $_ ) % 2 } qw( a b c d e ); say for @odds;
  • 6. my @odds = grep { ord($_) % 2 } qw( a b c d e );
  • 7. Which indices contain odd ords? my @chars = qw( a c f b q r n b d ); my @odds_by_idx = grep { ord( $chars[$_] ) % 2 } 0 .. $#chars;
  • 8. grep ● list_b = grep { code block } ( list_a ) ● Inside code block, $_ is it. ● If code block's return value is true, $_ is appended to list_b. ● As with foreach, $_ is an alias. ● list_b and list_a need not be arrays. ● Simple expressions may be used in place of code block.
  • 9. Simple expressions in place of code block @explosions = grep { /bkaboomb/i } @phrases; @explosions = grep /bkaboomb/i, @phrases; @ones = grep { $_ == 1 } @booleans; @ones = grep $_ == 1, @booleans; ● If it can't be expressed as a simple expression, use a code block. ● Expression form requires a comma.
  • 10. Transforming a list sub chars_to_ords { my @ords; foreach ( @_ ) { push @ords, ord $_; } return @ords; } my @ord_vals = chars_to_ords( qw( a b c d e ) );
  • 11. Transforming a list with map sub chars_to_ords { my @ords; foreach ( @_ ) { push @ords, ord $_; } return @ords; } my @ordinals = chars_to_ords( qw( a b c d e ) ); my @ordinals = map { ord $_ } qw( a b c d e );
  • 12. my @ordinals = map { ord $_ } qw( a b c d e );
  • 13. Lists don't have to be arrays say for map { ord } qw( a b c d e );
  • 14. map ● list_b = map { code block } ( list_a ) ● Inside code block, $_ is it. ● code block's return value is appended to list_b. ● As with foreach, $_ is an alias. ● list_b and list_a need not be arrays. ● code block is a subroutine; no last, no next. ● Skip current iteration by returning an empty list.
  • 15. Simple expressions don't require code blocks. say for map ord, qw( a b c d e ); # The expression form requires a comma.
  • 16. Chaining is legal (even encouraged) say for map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, ord fc $_ ] } qw( a b c d e ); # The Schwartzian Transform.
  • 17. Sort? @sorted = sort @unsorted; @sorted = sort { $a <=> $b } @unsorted; # Ascend, numeric @sorted = sort { $b <=> $a } @unsorted; # Descend, numeric @sorted = sort { $a cmp $b } @unsorted; # Ascend, stringy @sorted = sort { $a <=> $b || $a cmp $b } @unsorted; # Ascending numeric, then stringy. @sorted = sort { $a->{name} cmp $b->{name} } @unsorted;
  • 18. List::Util $first_one = first { /^kaboomb/i } @haystack; $sum = reduce { $a + $b } @numbers; $max = reduce { $a > $b ? $a : $b } @numbers;
  • 19. List::MoreUtils $has_quiche = any { /bquicheb/ } @foods; # T/F $all_unicorns = all { $_ eq 'unicorn' } @animals; # T/F @joint_incomes = pairwise { $a + $b } @his, @hers; @evens_odds = part { $_ % 2 } 1 .. 9; # LOLs
  • 20. List::MoreUtils “natatime” my @alphabet = ( 'a' .. 'z' ); my $iterator = natatime 3, @alphabet; while( my @chars = $iterator->() ) { print “@charsn”; } __END__ a b c d e f … y z
  • 21. List::MoreUtils ● Too many to mention them all. – See https://metacpan.org/module/List::MoreUtils
  • 22. Resources ● perldoc -f grep ● perldoc -f map ● perldoc -f sort ● perldoc List::Util ● https://metacpan.org/module/List::MoreUtils
  • 23. Salt Lake Perl Mongers http://saltlake.pm.org Slides on slideshare.net http://www.slideshare.net/daoswald/perls-functional-functions