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

Using Perl Modules

ynonperek
November 06, 2011

Using Perl Modules

Effective perl programming involves using modules instead of reinventing the wheel. This keynote is a sightseeing tour in some core and cpan modules solving common problems

ynonperek

November 06, 2011
Tweet

More Decks by ynonperek

Other Decks in Programming

Transcript

  1. Agenda ✤ Core Modules Review ✤ Extra Modules Review ✤

    Modules Recommendations Monday, December 12, 2011
  2. Core Modules ✤ English ✤ Fatal ✤ IO::File ✤ File::Find

    ✤ Getopt::Std (Getopt::Long) ✤ Storable ✤ Term::ANSIColor Monday, December 12, 2011
  3. 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
  4. 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
  5. 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
  6. Core: IO::File use strict; use warnings; use IO::File; my $filename

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

    = shift or die "Usage: $0 <filename>"; 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. Exception::Class ✤ Normal exception handling is performed with $@ ✤

    Disadvantages: ✤ Hard to differentiate the errors ✤ Unfriendly syntax Monday, December 12, 2011
  18. 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
  19. 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
  20. 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
  21. Hello Tk use strict; use warnings; use Tk; my $w

    = MainWindow->new; $w->Label(-text => "Hello World")->pack; MainLoop; Monday, December 12, 2011
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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('<<ListboxSelect>>', sub { my ($index) = $l->curselection; print "Selected $index\n"; }); MainLoop; Monday, December 12, 2011
  28. 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
  29. Modules Recommendations ✤ Spreadsheet::WriteExcel ✤ Log::Fine, Log::Fast, Log::Tiny ✤ DBIx::Class,

    Dancer, Moose ✤ File::Slurp ✤ Task::Kensho Monday, December 12, 2011