Download presentation
Presentation is loading. Please wait.
1
1.1.2.8.2 - Intermediate Perl - References
Intermediate Perl – Session 2 references - continued code references persistance data caching symbolic references a few words against their use 6/16/2018 Intermediate Perl - References
2
1.1.2.8.2 - Intermediate Perl - References
Last Time \$ \% () [] {} 6/16/2018 Intermediate Perl - References
3
1.1.2.8.2 - Intermediate Perl - References
Code References we have seen scalar, array and hash references code references point to subroutines – code you can actually execute remember that & is the sigil for a subroutine sub peelme { print shift,"is peeled"; } peelme("banana"); my $peelme_ref = \&peelme; print $peelme_ref; &{$peelme_ref}("papaya"); &$peelme_ref("another papaya"); $peelme_ref->("another banana"); banana is peeled CODE(0x80cdaa8) papaya is peeled another papaya is peeled another banana is peeled 6/16/2018 Intermediate Perl - References
4
Reference Syntax To-Date
scalar $x array @a hash %h functions &f reference $x_ref = \$x $a_ref = $h_ref = \%h $f_ref = \&f dereference $$x_ref @$a_ref $a_ref->[ ] %$h_ref $h_ref->{ } &$f_ref $f_ref->( ) 6/16/2018 Intermediate Perl - References
5
Creating Anonymous Subroutines
Just like [ ] and { }, you can create anonymous subroutines with sub { } Think of sub { } as an operator, not a declaration – therefore need ; at end my $square = sub { $_[0]**2 }; print $square->(2); print $square->(3); 4 9 declaration operator sub square { $_[0]**2; } print square(2); print square(3); my $square = sub { $_[0]**2 }; print $square->(2); print $square->(3); 6/16/2018 Intermediate Perl - References
6
Reference Syntax Table
list (1,2,3) hash (one=>1,two=>2) functions sub square { $_[0]**2 } regular reference @a = (1,2,3) $a_ref = %h = (one=>1,two=>2) $h_ref = \%h sub square { $_[0]**2;} $square_ref = \□ anonymous $a = [1,2,3]; $h = {one=>1,two=>2}; $square = sub {$_[0]**2}; 6/16/2018 Intermediate Perl - References
7
Uses of Anonymous Subroutines
use anonymous subroutines to make a list of functions decide which function to run at run-time great for sorts = qw( a b c q 12 01); my $sort_by_num = sub { $a <=> $b }; my $sort_by_string = sub { $a cmp $b }; my $sort_by_shuffle = sub { rand() <=> rand() }; print sort print sort print sort Argument "a" isn't numeric in ncmp at ./coderef line 54. Argument "b" isn't numeric in ncmp at ./coderef line 54. Argument "c" isn't numeric in ncmp at ./coderef line 54. Argument "q" isn't numeric in ncmp at ./coderef line 54. q b a c a b c q q 2 b 12 a c 1 4 3 my $sort_by_num_safe = sub { ($a =~ /\D/ || $b =~ /\D/) ? $a cmp $b : $a <=> $b }; print sort # a b c q 6/16/2018 Intermediate Perl - References
8
1.1.2.8.2 - Intermediate Perl - References
Flexible Sorting sometimes you don’t know what you’re about to sort and you want to do it properly we’ll cover more funky sorting at another time = qw( a b c q 12 01); if(grep($_ =~ { print sort } else { print sort } 6/16/2018 Intermediate Perl - References
9
1.1.2.8.2 - Intermediate Perl - References
Function Templates generate functions which behave similarly by transforming a single declaration one function, many behaviours create functions by passing default arguments to a function template set default arguments then forget about them! sub make_stove { my $heat = shift; return sub { print shift,"is cooked on",$heat,"heat" }; } my $small_stove = make_stove("low"); my $large_stove = make_stove("high"); $small_stove->("milk"); $large_stove->("water"); milk is cooked on low heat water is cooked on high heat 6/16/2018 Intermediate Perl - References
10
1.1.2.8.2 - Intermediate Perl - References
A Template Factory Let’s make a hash of functions What’s in %stoves? Sometimes data structures can get the best of us modules exist to pretty-print data structures = qw(tiny small medium large nuclear); my %stoves; = map { make_stove($_) $stoves{tiny}->(“socks"); $stoves{nuclear}->("bacon"); sock is cooked on tiny heat bacon is cooked on nuclear heat 6/16/2018 Intermediate Perl - References
11
Data::Dumper – debugger’s friend
One of the many very useful modules I’ll focus on modules at another time for now, just think of them as libraries of functions which you can call on Output of Data::Dumper can be passed to eval { } man Data::Dumper to read documentation use Data::Dumper; my $complex = {one=>1,two=>{a=>"amiable",b=>"burdensome",c=>[qw(coy cute)]}}; print Dumper($complex); $VAR1 = { 'two' => { 'a' => 'amiable', 'b' => 'burdensome', 'c' => [ 'coy', 'cute' ] }, 'one' => 1 }; 6/16/2018 Intermediate Perl - References
12
1.1.2.8.2 - Intermediate Perl - References
Looking into %stove What’s in the stove? $VAR1 = { 'medium' => sub { "DUMMY" }, 'small' => sub { "DUMMY" }, 'nuclear' => sub { "DUMMY" }, 'large' => sub { "DUMMY" }, 'tiny' => sub { "DUMMY" } }; use Data::Dumper; print Dumper(\%stove) 6/16/2018 Intermediate Perl - References
13
1.1.2.8.2 - Intermediate Perl - References
Persistence How do you store data between invocations of a script? text file XML database serialized data structure Sometimes it takes a long time to arrange data in memory just the way you like How do you debug step B without repeating the lengthy step A? do something with complex data structure (sort, calculate, etc) 10 min parse/organize in complex data structure 10 sec input data (e.g. text) A B 6/16/2018 Intermediate Perl - References
14
Storable - store/retrieve
The Storable module writes a data structure from memory onto disk – directly create and store my $complex = {one=>1,two=>{a=>"amiable",b=>"burdensome",c=>[qw(coy cute)]}}; use Storable; store($complex,"complex.cache"); » ls total 16 -rwxr-xr-x 1 martink users :00 coderef -rw-r--r martink users :16 complex.cache -rwxr-xr-x 1 martink users :16 getcomplex -rwxr-xr-x 1 martink users :16 makecomplex retrieve and use $VAR1 = { 'two' => { 'a' => 'amiable', 'b' => 'burdensome', 'c' => [ 'coy', 'cute' ] }, 'one' => 1 }; use Storable; use Data::Dumper; my $complex = retrieve("complex.cache"); print Dumper($complex); 6/16/2018 Intermediate Perl - References
15
Storable - freeze/thaw
In addition to writing serializing data to disk, you can serialize it to a list or string Use freeze/thaw to include data structures in URLs encrypt first! my $complex = {one=>1,two=>{a=>"amiable",b=>"burdensome",c=>[qw(coy cute)]}}; use Storable; my $datacan = freeze($complex); = unpack(“C*”,$datacan); my $datacan_reconstitute = print Dumper(thaw($datacan_reconstitute)); $VAR1 = { 'two' => { 'a' => 'amiable', 'b' => 'burdensome', 'c' => [ 'coy', 'cute' ] }, 'one' => 1 }; 6/16/2018 Intermediate Perl - References
16
1.1.2.8.2 - Intermediate Perl - References
Cache::Cache If you would like to implement an expiring data cache using Storable – don’t use Cache::FileCache Using this module you can associate complex data structures with expiring cache keys 6/16/2018 Intermediate Perl - References
17
1.1.2.8.2 - Intermediate Perl - References
Symbolic References Dangerous, but we’ll cover them Think of these as anologous to symbolic links on a UNIX file system point to names, not inodes change name of referent and symbolic link breaks in contrast, the references we have been talking about are hard references Using a string or a number as a reference produces a symbolic reference my $fruit = “banana”; $$fruit = “yellow”; # sets $banana = “yellow”; ${$fruit} = "rotting"; # sets $banana = “rotting” ${$fruit . "rama"} = "not a fruit"; # sets $bananarama = “not a fruit” sub bananajuice { print "very sticky"; } &{$fruit . "juice"}; # calls function bananajuice 6/16/2018 Intermediate Perl - References
18
strict VS no strict ‘refs’
you should always start all your script using the strict pragma if you want to use symbolic references, you must include why are symbolic references so evil? use strict; use strict; no strict ‘refs’; 6/16/2018 Intermediate Perl - References
19
Say No To Symbolic References
references spring into existence when used without initialization what would have happened if $x was already defined? In other words, you expect to use a variable as a reference and it conspires against you to set the value of a named variable use strict; my $x; # some scalar @{$x} = (1,2,3); # $x is now an array reference use strict; no strict ‘refs’; my $x; # some scalar $x = “numbers”; @{$x} = (1,2,3); is now a list 6/16/2018 Intermediate Perl - References
20
Slices with References
References and slices slice notation my $hash; $hash->{one} = 1; $hash->{two} = 2; $hash->{three} = 3; my $hash; @$hash{qw(one two three)} = (1,2,3) my $array; $array->[0] = “one”; $array->[1] = “two”; $array->[2] = “three”; my $array; @$array[0,1,2] = qw(one two three); 6/16/2018 Intermediate Perl - References
21
1.1.2.8.2 - Intermediate Perl - References
Teaser What do these refer to? $h is a hash ref $h is a hash and $h{KEY} holds scalar reference e.g. $h{KEY} = \42 $h is a hash ref and $h->{KEY} holds a scalar reference e.g. $h->{KEY} = \42 $$h{KEY} ${$h}{KEY} $h->{KEY} ${$h{KEY}} ${$h->{KEY}} 6/16/2018 Intermediate Perl - References
22
1.1.2.8.2 - Intermediate Perl - References
Common Errors You are likely to see something like this unless you are using symbolic references You are trying to dereference a variable that is NOT a reference, but a simple scalar Can't use string ("555") as a SCALAR ref while "strict refs" in use at ./recipies line 40. or Can't use string ("555") as an ARRAY ref while "strict refs" in use at ./recipies line 40. my $x = “hello”; # ERROR but you don’t get an error if you have no strict ‘refs’ – avoid symbolic references 6/16/2018 Intermediate Perl - References
23
1.1.2.8.2 - Intermediate Perl - References
Introduction to Perl – Session 1 train eyes to distinguish {} and [] {} is for HASHES [] is for ARRAYS mnemonic: CURLY HASHES SQUARE ARRAYS 6/16/2018 Intermediate Perl - References
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.