160 likes | 280 Views
More Perl. Strings References Complex data structures Multidimensional arrays Subprograms Perl OOP Methods Constructors and Instances Inheritance. Strings. Array of strings @guys = qw (Al Bob Cy); # instead of @guys = ("Al", "Bob", "Cy"); Concatenation
E N D
More Perl • Strings • References • Complex data structures • Multidimensional arrays • Subprograms • Perl OOP • Methods • Constructors and Instances • Inheritance
Strings • Array of strings @guys = qw(Al Bob Cy); # instead of @guys = ("Al", "Bob", "Cy"); • Concatenation • join(separator, list) join(":", "313", "is", "ok"); # 313:is:ok • Splitting • split(/pattern/, string) split(/:/, "313:is:ok"); # ("313","is","ok") split(/[:;]/, "313:is;ok"); # ("313","is","ok") • Replacement $text =~ s/foo/bar/; # replaces 1st foo by bar $text =~ s/\"//g; # deletes all quotes • rich pattern matching regular expressions
Boolean • Values equivalent to "false" • undef • "" # since it can represent undef • 0 # since it can represent undef • 0.0 # since it can represent 0 • "0" # since it can represent 0 • Everything else is equivalent to "true"
References • References are pointers to data structures • References are needed • Complex data structures • Build as arrays and hashes whose elements are references • Parameter passing • Denoted by \ my $scalar = 313; my @array = qw(ics 313); my %hash = (dept => "ics", course => 313); # references my $ref_scalar = \$scalar; my $ref_array = \@array; my $ref_hash = \%hash;
References to Arrays and Hashes • References to arrays and hashes can be initialized directly • Arrays • my $ref_courses = [313, 415]; • Hashes • my $ref_grades = {313 => "A-", 415 => "A+"}; • Note the different bracketing • These are also called anonymous references
Dereferencing • Dereferenced with ${}, @{} or %{} print ${$ref_scalar}; # prints $scalar $len = @{$ref_array}; # gets length of @array keys(%{$ref_myHash}); # keys of %hash • Another way to dereference is with -> $ref_array->[0] $ref_hash->{"key"}
Multidimensional Arrays • Multidimensional array is an • Array of references to subarrays my $matrix = [[1,0], [0,1], [0,0]]; • Elements can be accessesed directly print "m[1,0]: $matrix->[1][0]"; • Another way is $matrix->[1]->[0]; • Also • An array can hold references to hashes • A hash can hold references to arrays
Subprograms • Syntax sub name {…} • Parameters are accessible via array @_ my ($p1, $p2, $p3) = @_; # same as $p1 = @_[0] etc. • shift returns next parameter my $p1 = shift; my $p2 = shift; • Subprograms return a value • it not explicit, last expression is returned • Example sub square { my $num = shift; return $num * $num; }
Pass-by-Reference • All parameters are passed as one flattened array • Elements of scalars are concatenated! • Solution • Pass references to arrays or hashes my @v1 = (1,2,3); my @v2 = (4,5,6); my $product = product(\@v1,\@v2); • Dereference elements of parameter array within the subprogram sub product { my ($vector1, $vector2) = @_; my $product = 0; foreach my $i (0..$#{$vector1}) { $product += $vector1->[$i] * $vector2->[$i]; } return $product; }
eval function • evalevaluates an arbitrary string • It accepts a string parameter, • Evaluates it, and • Returns the result • Example print "Enter expression: "; my $expression = <STDIN>; chop($expression); my $result = eval($expression); print "$expression = $result"; • Produces this sample output Enter expression: 254+12*25 254+12*25 = 554
References to Functions • References to functions can be • Created using \&name • Assigned to variables • Passed as parameters • Called using $ref_sub->() • Example sub do_it { # executes any subprogram! my $ref_sub = shift; # function reference to call return $ref_sub->(@_); # call it with remaining params } • Can be used as sub square {…} my $ref_square = \□ # reference to square sub my $result = do_it ($ref_square, 22); print "result = $result";
OOP in Perl • A Perl class is defined as a package/module • Package files have same name as the class and extension .pm • Methods are normal subprograms • Fields are defined and initialized in a constructor • A module must return "true" at the end 1; # this is the simplest • Example package Person; sub new {…} # constructor sub set_name {…} sub set_age {…} sub say_hi {…} 1;
Constructors • Constructor is subprogram called new my $guy = Person->new("Joe", 29); • It creates a reference to a hash that contains the fields • The fields' names are keys of the hash • The fields' values are values in the hash • Typically, the parameters initialize the fields • 1st parameter is the class name • It blesses the hash and returns reference to the hash • Example sub new { my $self = {}; # reference to hash ($self->{class},$self->{name},$self->{age}) = @_; # turn this into an instance; return it bless($self, $self->{class}); }
Methods • Declare the method as subprogram • Reference to the called object is the 1st parameter sub say_hi { my $self = shift; print "Hi, I'm $self->{name}."; print " I'm $self->{age} years old.\n"; } • Perl adds automatically the 1st parameter to the call $guy->say_hi();
Using a Class #!/usr/bin/perl use strict; use warnings; use Person; my $guy = Person->new("Joe", 29); $guy->say_hi; $guy->set_name("John"); $guy->set_age(31); $guy->say_hi;
Inheritance • Define superclass with use base • Overwrite methods • Use to access overwritten method in superclass my $self = shift; $self->SUPER::say_hi; • Example package Brudda; use base "Person"; sub say_hi { my $self = shift; print "Howzit, bra? "; $self->SUPER::say_hi; }