Perl, Object Orientation (and a little Graph Theory)
Nick Stylianou
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 1 Outline
Preliminaries (History, Resources) 1) The Perl Language 2) Object-Orientation (OO) in Perl 3) Example Application: Graph Theory Conclusions, Questions & Discussion
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 2 A Brief History of Perl
● Created by Larry Wall – Natural and Artificial Languages, Seattle Pacific University (1970s) – NASA JPL, System Development Corporation (SDC)→Unisys (1986) ● Perl v1.0 released in 1987 Free Software Foundation Award 1998 for the ● Perl v5.0 released in 1994 – “Perl” Advancement of Free Software – v5.6 (2000) – Unicode, 64-bit, standardised version numbering – v5.8 (2002) – Unicode, I/O, Threads, widely distributed – Current stable production version 5.24 (2016) ● Perl 6 specification proposed in 2000
– redesign, not backwards-compatible; implementations (Pugs, Rakudo)
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 3 Resources
http://www.perl.org/
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 4 Download
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 5 Documentation
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 6 Community
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 7 Add-On Modules
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 8 1) The Perl Language
● “Hello world!” & the Perl philosophy ● Data Structures – Primitive Data Types and Common Code Patterns ● References (Pointers)
● Modularity – Subroutines and Packages
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 9 “Hello world” & the Perl philosophy
print “Howdy, world!\n” ← that’s it !!! (p. 1)
● “Perl is designed to make the easy jobs easy, without making the hard jobs impossible.” (p. ix)
● “With Perl you’re free to do The Right Thing, however you care to define it.” (p. 1)
● “If you’re starting to get the feeling that much of Perl culture is governed by mere convention, then you’re starting to get the right feeling...” (p. 278)
“The Camel Book” Larry Wall et al., Programming Perl (1996)
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 10 Best Practice “Hello world”
helloworld.pl #!/usr/bin/perl#!/usr/bin/perl useuse v5.10;v5.10; useuse strict;strict; useuse warnings;warnings; printprint "Hello"Hello world!\n";world!\n"; exitexit 0;0;
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 11 Data Structures: Primitive Data Types ● Scalars $a = 3; $price = 5.8; $c = “orange”; print $a; # prints 3
● Arrays (Lists) @a = (10,20,30,40,”banana”); $a[5] = 60; print $a[0]; # prints 10 @b = @a[1..3]; # @b = (20,30,40)
● Hashes key value %price = ( espresso => 1.8 , latte => 2.0 ); $price{tea} = 1.5; print $price{espresso}; # prints 1.8
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 12 Common Code Patterns: Arrays my ($x,$y,$z) = (0,0,0); # my $x=0; my $y=0; my $z=0; ($a,$b) = ($b,$a); # swaps values of $a and $b my @a = … for (my $i=0; $i <= $#a; $i++) { $a[$i]++; } for (my $i=0; $i < scalar @a; $i++) { $a[$i]++; } foreach my $e (@a) { $e++; } my $x = pop @a; push @a, $y; # stack my $x = shift @a; unshift @a, $y; # queue
The use of my is encouraged for strict lexical scoping – use strict
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 13 Common Code Patterns: Hashes
foreach my $k (keys %price) { $price{$k}*=1.2; } foreach my $k (sort keys %price) { print … }
● Take care with quotes:
$price{latte} ≍ $price{“latte”} ≍ $price{‘latte’} $price{$k} ≍ $price{“$k”} ≭ $price{‘$k’}
● “defined” and “exists”: value key defined $hash{key} exists $hash{key} $hash{key} = undef; ✘ ✔ delete $hash{key}; ✘ ✘
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 14 Compound Data Structures
● Arrays of Arrays (multi-dimensional arrays): my @a=(); u foreach my $t (0..9) { 0 1 2 3 … 0 0 1 2 3 foreach my $u (0..9) { 1 10 11 12 13 t $a[$t][$u] = (10*$t)+$u; } } 2 20 21 22 23 print $a[5][3]; # prints 53 3 30 31 32 33 … ● Hashes of Hashes (nested hashes): x my %h=(); r g b … foreach my $y (‘a’,’b’,’c’,’d’) { a ar ag ab foreach my $x (‘r’,’g’,’b’) { b br bg bb y $h{$y}{$x} = “$y$x”; } } c cr cg cb print $h{‘c’}{‘r’}; # prints “cr” d dr dg db …
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 15 References (Pointers)
● Obtain a (hard) reference with the \ operator $s = “r”; @a = (); %h = (); $p = \$s; $q = \@a; $r = \%h;
● De-reference with {…} $t = ${$p}; @b = @{$q}; %g = %{$r}; $t = $$p; $u = $a[0]; $v = $h{key}; (soft ref) $u = ${$q}[0]; $v = ${$r}{key}; or the -> operator: $u = $q->[0]; $v = $r->{key};
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 16 More References
● Compound Arrays and Hashes $a[5][3] ≍ $a[5]->[3] $h{c}{r} ≍ $h{c}->{r}
● Anonymous Arrays and Hashes my @a=(); $a[0] = ”x”; my $a=[]; $a->[0] = “x”;
my %h=(); $h{key} = 1; my $h={}; $h->{key} = 1;
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 17 Modularity: Subroutines
● A subroutine (function) is a named code block ● It returns the value of the last evaluated statement – the return statement makes this explicit ● Arguments are passed in as the array @_ – call-by-reference vs call-by-value (shift, assign) – @_ is a single flattened array
● to maintain identities of distinct arrays, use references
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 18 Subroutine Example
my ($a,$b) = (1,2); # 2 scalars my @a=(1,2,3); my @b=(4,5,6); # 2 arrays foo($a,$b,@a,@b);
# adds the sum of first two args to # each of the remaining args sub foo { my ($x,$y) = (shift @_, shift); foreach my $e (@_) { $e += $x+$y; } }
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 19 Packages – Basic Structure
MyLib.pm packagepackage MyLib;MyLib;
1;1; app.pl sub identify sub identify use MyLib; {{ use MyLib; …… printprint "MyLib\n";"MyLib\n"; } } MyLibMyLib::::identify();identify(); ……
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 20 The Perl Language – Recap
● 3 Primitive Data Types scalars $ , arrays (lists) @ [ ] , hashes % { } =>
● Code Patterns for/foreach , push/shift , keys %h , quotes, defined / exists
● Compound Data Structures arrays of arrays , hashes of hashes
● References \ , ${$p} @{$q} %{$r} -> , anonymous arrays/hashes: $a=[ ] $h={}
● Subroutines sub , return , my , @_ (flattened list) , call by reference / value
● Packages package , use , ::
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 21 2) Object Orientation in Perl
● Constructors ● Composition ● Attributes ● Inheritance
● Methods ● Abstraction
● Initialisation
● OO Frameworks
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 22 Constructors
app.pl useuse MyClass;MyClass; …… MyClass.pm $instance$instance == newnew MyClass()MyClass();; packagepackage MyClassMyClass;; ## MyClass->new();MyClass->new(); # MyClass::new(MyClass::); 1;1; # MyClass::new(MyClass::); …… subsub newnew {{ mymy $class$class == shift;shift; mymy $self$self == {};{}; bless($self,$class);bless($self,$class); returnreturn $self;$self; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 23 Attributes
MyClass.pm app.pl packagepackage MyClass;MyClass; useuse MyClass;MyClass; …… 1; 1; $instance$instance == newnew MyClass();MyClass(); sub new sub new printfprintf “%d\n”,“%d\n”, $instance->{id}$instance->{id};; { { …… mymy $class$class == shift;shift; mymy $self$self == {};{}; bless($self,$class);bless($self,$class); $self->{id}$self->{id} == 1;1; returnreturn $self;$self; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 24 Methods: Accessors
app.pl useuse MyClass;MyClass; … MyClass.pm … $instance$instance == newnew MyClass();MyClass(); …… subsub newnew printfprintf “%d\n”,“%d\n”, $instance->getID()$instance->getID();; {{ …… mymy $class$class == shift;shift; mymy $self$self == {};{}; bless($self,$class);bless($self,$class); $self->{id}=1;$self->{id}=1; returnreturn $self;$self; }}
subsub getIDgetID {{ mymy $self=shift;$self=shift; returnreturn $self->{id};$self->{id}; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 25 Methods: Modifiers
app.pl MyClass.pm useuse MyClass;MyClass; …… …… subsub newnew $instance$instance == newnew MyClass();MyClass(); { { $instance->setID(5); mymy $class$class == shift;shift; $instance->setID(5); mymy $self$self == {};{}; printf “%d\n”, $instance->getID(); bless($self,$class); printf “%d\n”, $instance->getID(); bless($self,$class); …… $self->$self->setID(1)setID(1);; returnreturn $self;$self; }}
subsub getIDgetID {{ mymy $self=shift;$self=shift; returnreturn $self->{id};$self->{id}; }} subsub setIDsetID {{ mymy $self=shift;$self=shift; $self->{id}=shift;$self->{id}=shift; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 26 Methods: Combined
app.pl MyClass.pm useuse MyClass;MyClass; …… … sub new … sub new $instance$instance == newnew MyClass();MyClass(); {{ mymy $class$class == shift;shift; $instance->id(5);$instance->id(5); mymy $self$self == {};{}; bless($self,$class);bless($self,$class); printfprintf “%d\n”,“%d\n”, $instance->id$instance->id;; $self->$self->id(1)id(1);; …… returnreturn $self;$self; }}
subsub idid ## multi-purposemulti-purpose accessor/modifieraccessor/modifier {{ mymy $self=shift;$self=shift; returnreturn (@_)(@_) ?? $self->{id}=shift$self->{id}=shift :: $self->{id}$self->{id} ;; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 27 Initialisation
MyClass.pm app.pl … … useuse MyClass;MyClass; sub new sub new …… { { $instance$instance == newnew MyClass();MyClass(); mymy $class$class == shift;shift; my $self = {}; my $self = {}; $instance->id(5);$instance->id(5); bless($self,$class);bless($self,$class); $self->_init();$self->_init(); printfprintf “%d\n”,“%d\n”, $instance->id;$instance->id; returnreturn $self;$self; …… }}
subsub _init_init underscore indicates {{ my $self = shift; “private” method my $self = shift; by convention only $self->$self->id(1)id(1);; }} ……
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 28 Parameterised Initialisation
app.pl MyClass.pm …… …… useuse MyClass;MyClass; subsub newnew {{ $instance$instance == newnew MyClass(MyClass( idid =>=> 55 );); mymy ($class,($class,%param%param)) == @_;@_; mymy $self$self == {};{}; printfprintf “%d\n”,“%d\n”, $instance->id;$instance->id; bless($self,$class);bless($self,$class); …… $self->_init($self->_init(%param);%param); returnreturn $self;$self; }}
subsub _init_init {{ mymy ($self,($self,%param%param)) == @_;@_; $self->id($self->id( (exists(exists $param{id})$param{id}) ?? $param{id}$param{id} :: 11 );); }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 29 Object-Orientation – Recap1
● Constructors: – A class is a package with a constructor subroutine (“new”) – An instance is a reference to a blessed anonymous hash ● Attributes are the key-value pairs of this hash ● Methods are additional subroutines ( invoked with -> ): – Access/Modify attributes (combined) – distinction: instance methods ($self), class methods ($class) – notion of private methods by convention only ( _ prefix ) ● Initialisation – Separate from construction – Parameterised initialisation (using key-value pairs)
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 30 Composition: Objects within Objects app.pl
…… useuse MyClass;MyClass; useuse MyOtherclass;MyOtherclass;
$instance$instance == newnew MyClass(MyClass( idid =>=> 5,5, part => new MyOtherclass( index => 1 ) MyClass.pm part => new MyOtherclass( index => 1 ) );); …… subsub _init_init printfprintf “%d\n”,“%d\n”, $instance->$instance->partpart->index;->index; {{ …… mymy ($self,%param)($self,%param) == @_;@_; $self->part($self->part( (exists(exists $param{part})$param{part}) ?? $param{part}$param{part} :: newnew MyOtherclass()MyOtherclass() );); }} subsub partpart ## multi-purposemulti-purpose accessor/modifieraccessor/modifier {{ mymy $self=shift;$self=shift; returnreturn (@_)(@_) ?? $self->{$self->{partpart}=shift}=shift :: $self->{$self->{partpart}} ;; }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 33 Inheritance… (almost!)
packagepackage MySubclassMySubclass;; …… useuse parentparent 'MyClass';'MyClass';
subsub newnew …… {{ useuse MyClass;MyClass; packagepackage MyClassMyClass;; mymy ($class,%param)($class,%param) == @_;@_; useuse MySubclass;MySubclass; …… mymy $self$self == {};{}; bless($self,$class); subsub newnew bless($self,$class); mymy $v$v == newnew MyClass(…);MyClass(…); {{ $self->_init(%param);$self->_init(%param); my ($class,%param) = @_; return $self; my ($class,%param) = @_; return $self; mymy $n$n == newnew MySubclass(…);MySubclass(…); mymy $self$self == {};{}; }} bless($self,$class);bless($self,$class); $self->_init(%param);$self->_init(%param); subsub _init_init returnreturn $self;$self; {{ … but id isn’t }} mymy ($self,%param)($self,%param) == @_;@_; initialised !!! $self->$self->namename(( $param{$param{namename}} );); subsub _init_init }} {{ mymy ($self,%param)($self,%param) == @_;@_; $self->$self->idid(( $param{$param{idid}} );); }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 34 Inheritance
packagepackage MySubclassMySubclass;; …… useuse parentparent 'MyClass';'MyClass';
subsub newnew {{ packagepackage MyClassMyClass;; mymy ($class,%param)($class,%param) == @_;@_; …… mymy $self$self == newnew MyClass(%param)MyClass(%param);; sub new bless($self,$class); sub new bless($self,$class); …… {{ $self->_init(%param);$self->_init(%param); use MyClass; my ($class,%param) = @_; return $self; use MyClass; my ($class,%param) = @_; return $self; useuse MySubclass;MySubclass; mymy $self$self == {};{}; }} bless($self,$class); bless($self,$class); mymy $v$v == newnew MyClass(…);MyClass(…); $self->_init(%param);$self->_init(%param); subsub _init_init returnreturn $self;$self; {{ mymy $n$n == newnew MySubclass(…);MySubclass(…); }} mymy ($self,%param)($self,%param) == @_;@_; $self->name($self->name( $param{name}$param{name} );); subsub _init_init }} {{ mymy ($self,%param)($self,%param) == @_;@_; $self->id($self->id( $param{id}$param{id} );); }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 35 Inheritance
packagepackage MySubclass;MySubclass; …… useuse parentparent 'MyClass';'MyClass';
subsub newnew { { … packagepackage MyClassMyClass;; mymy ($class,%param)($class,%param) == @_;@_; … … my $self = {}; useuse MyClass;MyClass; … my $self = {}; use MySubclass; subsub newnew bless($self,$class);bless($self,$class); use MySubclass; { $self->_init(%param);$self->_init(%param); { my $v = new MyClass(…); mymy ($class,%param)($class,%param) == @_;@_; returnreturn $self;$self; my $v = new MyClass(…); mymy $self$self == {};{}; }} my $n = new MySubclass(…); bless($self,$class);bless($self,$class); my $n = new MySubclass(…); $self->_init(%param);$self->_init(%param); subsub _init_init returnreturn $self;$self; {{ }} mymy ($self,%param)($self,%param) == @_;@_; $self->SUPER::_init(%param);$self->SUPER::_init(%param); subsub _init_init $self->name($self->name( $param{name}$param{name} );); {{ }} mymy ($self,%param)($self,%param) == @_;@_; $self->id($self->id( $param{id}$param{id} );); }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 36 Abstraction
packagepackage MySubclass;MySubclass; …… useuse parentparent 'MyClass';'MyClass'; packagepackage MyClassMyClass;; ## abstractabstract subsub newnew …… {{ sub new my ($class,%param) = @_; …… sub new my ($class,%param) = @_; use MyClass; {{ my $self = {}; use MyClass; my $self = {}; use MySubclass; mymy ($class,%param)($class,%param) == @_;@_; bless($self,$class);bless($self,$class); use MySubclass; mymy $self$self == {};{}; $self->_init(%param);$self->_init(%param); my $v = new MyClass(); bless($self,$class);bless($self,$class); returnreturn $self;$self; my $v = new MyClass(); $self->_init(%param);$self->_init(%param); }} returnreturn $self;$self; mymy $n$n == newnew MySubclass();MySubclass(); }} subsub _init_init {{ subsub _init_init mymy ($self,%param)($self,%param) == @_;@_; {{ $self->SUPER::_init(%param);$self->SUPER::_init(%param); mymy ($self,%param)($self,%param) == @_;@_; $self->name($self->name( $param{name}$param{name} );); $self->id($self->id( $param{id}$param{id} );); }} }} subsub idid {{ …… }}
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 37 Object-Orientation – Recap2
● (Constructors, Attributes, Methods, Initialisation) –
Recap1
● Composition: – Objects within objects ● Inheritance: – use parent, SUPER:: – no subclass constructor ● Abstraction – no superclass constructor
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 38 Perl OO Frameworks: Moose
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 39 3) Example Application: Graph Theory
● Basic overview of graph theory ● Implementing graphs with: – Native Perl (hashes) – Object-Orientation – CPAN: The “Graph” module
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 40 Basic Overview of Graph Theory
● A graph is: – a collection of nodes (vertices)... – … connected by edges ● A graph can be: – undirected / directed – unweighted / weighted ● Graph Theory is the study of these structures and their properties.
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 41 A Graph as a Hash of Edges
graph.pl
mymy %edge=();%edge=(); openopen INFILE,"
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 42 Weighted Edges (Count) data.txt aa bb graph.pl $$ graph.plgraph.pl bb cc aa bb 22 c d ## buildbuild aa hashhash ofof graphgraph edgesedges b c 2 c d ... b c 2 cc aa ... cc aa 11 a b ## $edge{$from}{$to}$edge{$from}{$to} == 1;1; c d 1 a b $edge{$from}{$to}++; c d 1 bb cc $edge{$from}{$to}++; ......
## plainplain texttext outputoutput ofof graphgraph edgesedges ...... mymy $weight$weight == $edge{$from}{$to};$edge{$from}{$to}; printfprintf "%s\n","%s\n", join("\t",$from,to,join("\t",$from,to,$weight$weight);); ......
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 43 Weighted Edges (Sum)
$$ graph.plgraph.pl data.txt aa bb 99 bb cc 99 a b 5 graph.pl a b 5 cc aa 11 bb cc 77 c d 3 ## buildbuild aa hashhash c d 3 cc dd 33 ...... cc aa 11 ## mymy ($from,$to)($from,$to) == splitsplit "\t";"\t"; aa bb 44 mymy ($from,$to,($from,$to,$weight$weight)) == splitsplit "\t";"\t"; bb cc 22 ## $edge{$from}{$to}++;$edge{$from}{$to}++; $edge{$from}{$to}$edge{$from}{$to}+=$weight+=$weight;; ...... ## plainplain texttext outputoutput ...... mymy $weight$weight == $edge{$from}{$to};$edge{$from}{$to}; printfprintf "%s\n","%s\n", join("\t",$from,to,join("\t",$from,to,$weight$weight);); ......
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 44 Weighted Edges (Array) data.txt $ graph.pl aa bb 55 $ graph.pl a b 5:4 bb cc 77 a b 5:4 graph.pl b c 7:2 cc dd 33 b c 7:2 c a 1 cc aa 11 c a 1 ## buildbuild aa hashhash a b 4 cc dd 33 a b 4 ...... b c 2 b c 2 ## $edge{$from}{$to}+=$weight;$edge{$from}{$to}+=$weight; pushpush @{$edge{$from}{$to}},@{$edge{$from}{$to}}, $weight;$weight; ...... scalar(scalar( @{$edge{$from}{$to}}@{$edge{$from}{$to}} );); sum( @{$edge{$from}{$to}} ); # plain text output sum( @{$edge{$from}{$to}} ); # plain text output ...... mymy $weight$weight == join(‘:’,@{$edge{$from}{$to}})join(‘:’,@{$edge{$from}{$to}});; printfprintf "%s\n","%s\n", join("\t",$from,to,join("\t",$from,to,$weight$weight);); ......
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 45 Node Attributes
data.txt $$ graph.plgraph.pl a 3 a b graph.pl a 3 a b bb 44 bb cc c 4 c d mymy %edge=();%edge=(); c 4 c d my %node=(); dd 11 cc aa my %node=(); a b openopen INFILE,"
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 46 Node Attributes
graph.pl
mymy %edge=();%edge=(); mymy %node=();%node=(); openopen INFILE,"
Class Instance Attribute Value Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 47 Bespoke Classes MyGraph/Edge.pm packagepackage MyGraph::Edge;MyGraph::Edge;
1;1; MyGraph/Graph.pm package MyGraph::Graph; subsub newnew {{ …… }} package MyGraph::Graph; useuse MyGraph::Edge;MyGraph::Edge; graph.pl subsub getSourcegetSource {{ …… }} sub getDest { … } useuse MyGraph::Node;MyGraph::Node; use MyGraph::Graph; sub getDest { … } 1; use MyGraph::Graph; subsub getWeightgetWeight {{ …… }} 1; useuse MyGraph::Edge;MyGraph::Edge; …… sub new { … } sub new { … } mymy $g$g == newnew Graph();Graph(); …… MyGraph/Node.pm subsub addEdgeaddEdge {{ …… }} whilewhile (
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 48 Perl “Graph” Module
$$ cpancpan GraphGraph …… GraphGraph isis upup toto datedate (0.9704).(0.9704). $$
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 49 Perl “Graph” Module overover 300300 subroutines,subroutines, including:including:
add_edgeadd_edge add_weighted_edgeadd_weighted_edge add_edgesadd_edges add_weighted_edgesadd_weighted_edges add_vertexadd_vertex add_weighted_vertexadd_weighted_vertex add_verticesadd_vertices add_weighted_verticesadd_weighted_vertices add_pathadd_path add_weighted_pathadd_weighted_path
has_edgehas_edge has_edgeshas_edges has_vertexhas_vertex has_verticeshas_vertices has_pathhas_path has_cyclehas_cycle
is_cyclicis_cyclic is_acyclicis_acyclic is_directedis_directed is_undirectedis_undirected is_connectedis_connected is_strongly_connectedis_strongly_connected is_biconnectedis_biconnected is_weakly_connectedis_weakly_connected is_edge_connectedis_edge_connected is_edge_separableis_edge_separable is_transitiveis_transitive
transitive_closuretransitive_closure minimum_spanning_treeminimum_spanning_tree transpose_graphtranspose_graph ......
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 50 Perl & Graph Theory - Recap
● Graphs in native Perl using nested hashes:
– $class{instance}{attribute}=value (simple or complex) ● Object-Oriented implementation: – encapsulate functionality into packages/classes ● CPAN “Graph” module: – provides extensive graph theory functionality – follows Object-Oriented model typical of many CPAN modules
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 51 Conclusions
● While Perl is not strictly an “OO” platform... – applying OO principles exposes aspects of the paradigm – metaphor between nested hashes and OO classes – OO thinking shapes many CPAN modules
● understanding is helpful for using and contributing modules ● Perl philsophy: – favours convention over enforcement – context: local readability vs global consistency – programmer freedom / responsibility
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 52 Thank You !
Email: [email protected] Nick Stylianou
@nick_stylianou
Questions and Discussion?
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 53 “Hello world” & the Perl philosophy
● “Perl… was designed to work smoothly in the same way that natural language works smoothly.” (p. 2) open LOG,”>$logfile” or die “Failed to open $logfile”; die “Failed to open $logfile” unless open LOG,”>$logfile”; print LOG “Logging...\n” if $logging_enabled; $logging_enabled and print LOG “Logging...\n”; if ($logging_enabled) { print LOG “Logging...\n”; }
“The Camel Book” Larry Wall et al., Programming Perl (1996)
Advanced Programming Perl, Object Orientation (and a little Graph Theory) Nick Stylianou, Thursday 9th March 2017 Specialist Group 54