Slide 1

Slide 1 text

Coding With Modules The lazy coder’s guide to getting things done Monday, December 12, 2011

Slide 2

Slide 2 text

Agenda ✤ Core Modules Review ✤ Extra Modules Review ✤ Modules Recommendations Monday, December 12, 2011

Slide 3

Slide 3 text

Core Modules ✤ English ✤ Fatal ✤ IO::File ✤ File::Find ✤ Getopt::Std (Getopt::Long) ✤ Storable ✤ Term::ANSIColor Monday, December 12, 2011

Slide 4

Slide 4 text

Core: English Readable perl works Monday, December 12, 2011

Slide 5

Slide 5 text

Core: English ✤ Create english names for perl global variables ✤ $OS_ERROR instead of $! ✤ $EVAL_ERROR instead of $@ ✤ $PROGRAM_NAME instead of $0 use English; my $filename = $PROGRAM_NAME; open my $fh, "<", $filename or die $OS_ERROR; while (<$fh>) { print; } close $fh; Monday, December 12, 2011

Slide 6

Slide 6 text

Working With Files The Write Way Monday, December 12, 2011

Slide 7

Slide 7 text

Core: Fatal ✤ Automatically dies if an open or close fails ✤ Catch the exception using eval if needed ✤ For perl >= 5.10 use autodie instead use strict; use warnings; use Fatal qw/open close/; sub count_lines { my ($filename) = @_; my $lines = 0; open my $f, '<', $filename; $lines++ while (<$f>); close $f; return $lines; } Monday, December 12, 2011

Slide 8

Slide 8 text

Core: IO::File ✤ Easier file operations using OO like syntax ✤ Set no buffering using $fh->autoflush ✤ perldoc IO::Handler for full list of features Monday, December 12, 2011

Slide 9

Slide 9 text

Core: IO::File use strict; use warnings; use IO::File; my $filename = shift or die "Usage: $0 "; my $fh = IO::File->new($filename, "w"); for my $counter (1..10) { $fh->print("*" x $counter, "\n" ); } $fh->close; * ** *** **** ***** ****** ******* ******** ********* ********** Monday, December 12, 2011

Slide 10

Slide 10 text

Core: IO::File use strict; use warnings; use IO::File; my $filename = shift or die "Usage: $0 "; my $fh = IO::File->new($filename, "r"); while (my $line = <$fh>) { printf("%0.2d %s", $fh->input_line_number, $line); } $fh->close; Monday, December 12, 2011

Slide 11

Slide 11 text

Core: File::Find ✤ Traverse an entire directory tree executing a block of code for each file in the tree ✤ Can use to find text in files, count files, and any other operation ✤ Takes a code ref and a list of directories to search Monday, December 12, 2011

Slide 12

Slide 12 text

File::Find Example use strict; use warnings; use File::Find; my $ext = '.pl'; my $count = 0; # the wanted function is called once for every # path in the directory tree sub wanted { # $_ is the name of the current file $count++ if /$ext$/ } find(\&wanted, '.'); print "found $count pl files\n"; Monday, December 12, 2011

Slide 13

Slide 13 text

Core: Storable ✤ Allows storing and retrieving state from files ✤ simply store/retrieve data to/ from files use strict; use warnings; use Storable; my $data = { counter => 0 }; eval { $data = retrieve('state.bin'); }; $data->{counter}++; print $data->{counter}, "\n"; store($data, 'state.bin'); Monday, December 12, 2011

Slide 14

Slide 14 text

Working With The Terminal Monday, December 12, 2011

Slide 15

Slide 15 text

Core: Getopt::Std ✤ Read command line arguments from the user ✤ Use a : after the letter to specify it taking an argument ✤ No : after the letter means a boolean option use strict; use warnings; use Getopt::Std; use Data::Dumper; my %opts; getopts('oif:', \%opts); print Dumper(\%opts); Monday, December 12, 2011

Slide 16

Slide 16 text

Core: Term::ANSIColor ✤ print cool color stuff in the terminal ✤ use ‘print color’ to change terminal color ✤ use ‘print color reset’ to go back to normal use strict; use warnings; use Term::ANSIColor; my @colors = qw/red blue yellow magenta cyan/; foreach my $clr (@colors) { print color $clr; print "Cool im $clr\n"; print color 'reset'; } Monday, December 12, 2011

Slide 17

Slide 17 text

Lab #1 ✤ Write a perl that reads an entire directory tree (starting with the current directory). For every file it finds, check if the file has the phrase “holy grail” in it. ✤ Print the total number of files with that phrase ✤ Improve your app: print only files that were not printed on the previous run Monday, December 12, 2011

Slide 18

Slide 18 text

Lab #2 ✤ Implement a colored version of the cat utility ✤ Take color as an input switch ✤ Take file as argument ✤ Print the file’s contents in the specified color Monday, December 12, 2011

Slide 19

Slide 19 text

Extra Modules Power up your perl Monday, December 12, 2011

Slide 20

Slide 20 text

Agenda ✤ DateTime ✤ Try::Tiny ✤ Spreadsheet::ParseExcel Monday, December 12, 2011

Slide 21

Slide 21 text

DateTime Monday, December 12, 2011

Slide 22

Slide 22 text

Extra: DateTime ✤ Handle calendar information ✤ Does not parse dates ✤ Use for pretty printing and time calculations use strict; use warnings; use DateTime; my $now = DateTime->now; my $month = $now->month_name; print "We are in $month\n"; Monday, December 12, 2011

Slide 23

Slide 23 text

Some More Functions ✤ $date->ymd $date->dmy $date->hms ✤ $date->is_leap_year ✤ $dt = DateTime->from_epoch ( epoch => ... ) Full documentation: perldoc DateTime Monday, December 12, 2011

Slide 24

Slide 24 text

Try::Tiny When things go wrong Monday, December 12, 2011

Slide 25

Slide 25 text

Exception::Class ✤ Normal exception handling is performed with $@ ✤ Disadvantages: ✤ Hard to differentiate the errors ✤ Unfriendly syntax Monday, December 12, 2011

Slide 26

Slide 26 text

Try::Tiny use strict; use warnings; use Try::Tiny; try { die "good bye cruel world"; } # catch is optional catch { warn "Exception: $_"; } Monday, December 12, 2011

Slide 27

Slide 27 text

Try::Tiny ✤ Can also use if (/.../) inside catch block to treat exceptions differently ✤ Can also use finally ✤ perldoc Try::Tiny try { die "NetworkError"; } catch { if (/Network/) { warn 'network error'; } if (/File/) { warn 'file error'; } } Monday, December 12, 2011

Slide 28

Slide 28 text

Perl Tk User Interface For The Masses http://martin-achern.de/wgetgui/aria2gui.html Monday, December 12, 2011

Slide 29

Slide 29 text

UI Concepts ✤ App runs in a MainLoop ✤ Coding tasks: ✤ Initialize UI components ✤ Define event handlers (subroutine refs) ✤ Bind handlers to events Monday, December 12, 2011

Slide 30

Slide 30 text

Hello Tk use strict; use warnings; use Tk; my $w = MainWindow->new; $w->Label(-text => "Hello World")->pack; MainLoop; Monday, December 12, 2011

Slide 31

Slide 31 text

Tk Components ✤ Each component has attributes which define its behavior ✤ Attributes are provided in the call to new ✤ Use cget to read an attribute, Use configure to set ✤ Use pack to add a component to a container Monday, December 12, 2011

Slide 32

Slide 32 text

Attributes Example use strict; use warnings; use Tk; use List::Util qw/shuffle/; my @colors = qw/red blue green/; my $w = MainWindow->new; my $l = $w->Label(-text => "red")->pack; my $b = $w->Button(-text => "Click", -command => sub { my ($clr) = shuffle @colors; $l->configure(-text => $clr ); })->pack; MainLoop; Monday, December 12, 2011

Slide 33

Slide 33 text

Other Components ✤ Label: One line text label ✤ Button: A push button ✤ Checkbutton: A check box ✤ Entry: One line text entry ✤ Listbox: List widget ✤ Text: Long text widget Monday, December 12, 2011

Slide 34

Slide 34 text

Components Example use strict; use warnings; use Tk; my $w = MainWindow->new; $w->Label(-text => "File Finder")->pack; $w->Entry(-text => "Text To Find")->pack; $w->Listbox->pack; $w->Button(-text => "Find")->pack(-side => 'right'); $w->Button(-text => "Exit")->pack(-side => 'left'); MainLoop; Monday, December 12, 2011

Slide 35

Slide 35 text

Event Bindings ✤ Every Tk component may produce events ✤ At its simplest, every key or mouse button pressed is an event ✤ More complex widgets produce special events ✤ Use bind to bind with an event Monday, December 12, 2011

Slide 36

Slide 36 text

Watching Selection Change ✤ Use bind to listen for an event ✤ Events are marked inside << ... >> ✤ The second argument to bind is a subroutine ref used as calback use strict; use warnings; use Tk; my @colors = qw/red blue green white/; my $w = MainWindow->new; my $l = $w->Listbox->pack; $l->insert('end', @colors); $l->bind('<>', sub { my ($index) = $l->curselection; print "Selected $index\n"; }); MainLoop; Monday, December 12, 2011

Slide 37

Slide 37 text

Lab ✤ Write a simple text editor in Perl/Tk. ✤ User starts the app with a file name and sees entire file contents on screen inside a Text widget ✤ Provide “Save” and “Quit” buttons ✤ Extra: Save only if modified ✤ Extra: Provide “Open” button that opens another file Monday, December 12, 2011

Slide 38

Slide 38 text

Modules Recommendations ✤ Spreadsheet::WriteExcel ✤ Log::Fine, Log::Fast, Log::Tiny ✤ DBIx::Class, Dancer, Moose ✤ File::Slurp ✤ Task::Kensho Monday, December 12, 2011

Slide 39

Slide 39 text

Resources ✤ search.metacpan.org ✤ perldoc perlmodlib ✤ perldoc ✤ https://www.socialtext.net/perl5/recommended_cpan_modules Monday, December 12, 2011

Slide 40

Slide 40 text

Q & A Monday, December 12, 2011

Slide 41

Slide 41 text

Thank You ✤ Ynon Perek ✤ [email protected] ✤ ynonperek.com Monday, December 12, 2011