-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME
1513 lines (1022 loc) · 25.8 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Notes:
Instructor: brian d foy
Version: 3.1
Date: 10/14/2013
perldoc perlvar
perldoc -f eval
perldoc -q comma
perldoc perlop
http:://perldoc.perl.com
-------------------------------------------
Review of grep:
-------------------------------------------
my @numbers = 1..1000;
my @odd_numbers;
foreach (@numbers) {
push @odd_numbers, $_ if $_ % 2;
}
or
my @odd_numbers = grep $_ % 2, 1..1000;
my @result = grep expression, list;
As in foreach $_ is aliased to the elements of the original list, careful, don't change $_ unless you intend to change the original list.
also:
my @matching = grep /\bMinow\b/, <FILE>; # gets the matching lines
Perl Power Tools - adds perl implemenations of grep and other linux stuff to Windows. COOL ***
-------------------------------------------
Review of map:
-------------------------------------------
my @foods = qw/ COCONUTS Rice mangoes Wild_boar /;
my @good_case;
foreach (@foods) {
push @good_case, "\u\L$_";
}
or
my @good_case = map "\u\L$_", @foods;
Can be used inline.
print "The foods are:\n", map " $_\n", @good_case;
Its all list processing. Just like the linux pipeline.
Called the UNIX toolbox.
LISP - also very good at this...
Higher Order Perl - Mark Jas
Perl has 6 of the 7 things that define LISP.
Case Shifters in string interpretation.
Call a subroutine:
my @files &funct($_), glob "*";
my @strings = map &funct($_), <FILE>;
-------------------------------------------
Annomyous subroutine:
-------------------------------------------
my @strings = map {
my $copy = $_;
$copy =~ s/^\s+//;
$copy; # return
} <FILE>
($new = $orig) =~ s///;
$new = $orig =~ s///r; # 5.14 /r returns results instead of count.
@out = map { s/// } @in; # array of counts substitute
@out = map { s///r } @in; # array of strings with substitutes.
-------------------------------------------
Mapping one to many:
-------------------------------------------
my @file_names = glob "*";
my @names_and_sizes = map { $_, -s } @file_names;
my %size_of = @names_and_sizes;
# Shorter version
my %size_of = map { $_, -s } glob "*";
my @words = map split, <FILE>; # splits the whole file into words.
my @comments = map /#\s*(.*)/, <INPUT>; # a list of # comments
-------------------------------------------
Review of eval:
-------------------------------------------
String form - bad one, genearally execute string as perl code.
Block form -
eval {
open FH, $file or die "This is caught in $@";
some_sub_that_dies(); #This is caught too
}
if ($@) {
...
}
Does not trap normal execution, such as exit or warnings.
The code in the eval block must compile.
It doesn't catch syntax errors.
die "xxx"; # xxx file# line#
die "xxx/n" # xxx
-------------------------------------------
Introduction to References
-------------------------------------------
my @last_three = pop_n(3, @foos);
passed a n+1 item list 3, ?, ?, ?, ?, ...
my @last_three = pop_n(3, \@foos);
passes a 2 item list. 3, ref @foos
PeGS...
Write a Perl module to generate PeGS.
$ref = \@count
| ref >
| count >
===========
| * | ------------> 5
4
3
2
1
A reference is just a scalar.
sub pop_n {
my ($n, $array_ref) = @_;
...
}
$array_ref is just a "pointer" to the array.
Daily WTF.
printf "%${width}s\n"; # ahha here is the fix to $abc_abb where ${abc}_abb.
@array = @{$array_ref};
Its just about naming...
sub pop_n {
my ($n, $array_ref) = @_;
my @items;
for (1..$n) {
my $item = pop @{ $array_ref };
unshift @items, $item;
}
@items; #return value.
}
# Test it now...
my @foods = qw/ clam coconut fish /;
my @last_3 = pop_n(3 \@foods);
print "@foods\n";
If you pass in 0 for $n? 1..0 => undef, returns @items -> undef.
Additional ways to access an array:
my $count = @{$array_ref};
my $last = $#{$array_ref};
my @two = @{$array_ref} [1, 2];
Hash references:
my $ref = \%file_size;
${$ref}{item} = ???
@{$ref}[0]
Scalar references:
How to make perl release memory?
sub strip_span {
my $string_ref = shift;
$$string_ref =~ s/<\?span.*?>//s;
}
Passing a scalar by value creates a copy. Pass by reference is better for big data, think strings.
You can compare references to see if they point to the same data.
Modifying the array:
my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
check_required_items("gilligan", \@gilligan);
sub check_required_items {
my $who = shift;
my $items = shift;
my %items = map { $_, 1} @$items;
state @required = qw(preserver sunscreen water_botle jacket); # state requires 5.10. (similar to static, initialized the first time only.)
my @missing = ();
foreach my $item (@requried) {
unless (exists $items{$item}) {
print
push @missing, $item;
}
}
if (@missing) {
print "Adding @missing to @$items for $who.\n";
push @$items, @missing;
}
}
Defereferenceing with deeply nested structures gets very complicated.
Prefer to use the -> to do the dereference.
$all[2]->[1]->[0] = ${ ${ $all[2] } [1] }[0];
also you can use:
$all[2][1][0]
another way to build the hash:
@names = qw(skipper, gilligan, professor);
%all = map {
$_, \@{"$_"}
} @names;
#doesn't work in strict, there is another way too coming up.
#don't do that...
%main:: -> stash - tracks all the stuff.
foreach (keys %main::) {
next unless defined @{"$_"};
print "$_\n";
}
masteringperl.org -> new book by brian d foy.
intermediateperl.com -> this book.
How to use state actually?
state $required = [preserver sunscreen water_bottle life_jacket]; # should work.
--------------------------
References and Scoping:
--------------------------
my $ref = \@count;
my $ref2 = $ref;
or
my $ref2 = \@count;
Just a new name for the same reference.
When things go out of scope, the name dissapears, the data sticks around until all the references are released.
sub get_personal_info {
local $_;
my $who = shift;
open (FILE, "clothing-size") or die "Can't open clithing-size file: $!";
chomp($_ = <FILE>);
my @headings = split /\t/;
while(<FILE>) {
chomp;
my @data = split /\t/;
next unless $data[0] eq $who;
my %hash;
@hash{@headings} = @data; # Hash slice assigns each data to each key
close FILE;
return \%hash;
}
close FILE;
();
}
HoA -> Hash of Arrays
HoH -> Hash of Hashes
>> perldsc
----------------------
Auto-vivification:
----------------------
my %total_bytes;
while(<>) {
my ($source, $dest, $bytes) = split;
$total_bytes{$source}{$destination} += $bytes;
}
How to disable auto-vivication?
use autovivification;
calls import();
use x; => BEGIN {require x; x->import;}
no autovivificaiton;
no x; => BEGIN {require x; x->unimport;}
---------------
Destruction
---------------
Add a ref ++ refcount
Remove a ref -- refcount
Once the refcount is 0, perl may release the memory, may not be right a way....
Can cause problems where structures cross reference each other.
Stephen (Linked list in perl)
-----------------------
Prototypical Checking
-----------------------
if (ref $some eq ref [] ) { ... } # array ref
if (ref $some eq ref {} ) { ... } # hash ref
if (ref $some eq ref qr() ) { ... } # regex ref
-----------------------
Section 5: Manipulating Complex Data Structures
-----------------------
What is a good perl visual debugger?
log for perl
Debuggers:
Devel::REPL
Devel::hdb
-------------------------------------------
Printing a structured value for debugging
-------------------------------------------
Data::Dumper;
------------------
Add column names:
------------------
print Data::Dumper->Dump(
[ \%people, [ qw(a b c) ],
[ qw(*people *array)],
)
* means add the correct type.
Data::Dump::Streamer - has fancier features.
Data::Printer -
p %hash;
------------------
YAML:
------------------
use YAML;
print Dump( \%people, [qw(a b c)]);
Now it outputs YAML...
To get it back:
use YAML;
my ($people, $array) = Load( $string );
YAML never evals so its safer...
Its available in other languages
There are other implementations:
* YAML::Tiny
* YAML::Syck
Security issues:
CGI::SpecFile
DESTROY {
unlink $$_[0];
}
And Storable can be passed a string that can be iterpreted as this CGI::SpecFile class. Opps, you can unlink any file. YUCK.
----------------------------
Persistence with Storable
----------------------------
Sereal - Fixes all the known problems with Storable.
----------------------------
Subroutine References
----------------------------
Reduce repetition.
my $func_ref = \&func;
&func_ref();
&{$func_ref}();
&$func_ref();
$func_ref->(); # Added just before 5.04 released.
All these call the same function the same way...
Using multipe coderefs:
foreach my $greet_ref (\&a_greet, \&b_greet, \&c_greet) {
$greet_ref->();
}
----------------------------
Anonymous Subroutine:
----------------------------
my $func_ref = sub {
...
}
ASSIDE: (Cool use for state to get the loop counter.)
@output_list = map {
state $n = 0;
say "on element", $n++;
} @in;
----------------------------
Callbacks:
----------------------------
use File::Find;
sub what_to_do {
print "$File::Find::name found.\n";
}
my @starting_points = qw{ . };
find(\&what_to_do, @starting_points);
There are several more variables:
ASSIDE: find2perl -> creates a perl subroutine that works like the find linux call, but all native perl and often more efficent since doesn't pipe to output processing...
----------------------------
Lexical variables in a surrounding scope
----------------------------
use File::Find;
my ($total_files, $total_bytes) = (0,0);
find(
sub {
return if -l or not -f _; # Not a link or not a file
$total_files++;
$total_bytes += -s _;
},
"."
);
print "Total: $total_bytes bytes in $total_files files.\n";
----------------------------
Closures
----------------------------
my $callback;
{
# In the private scope
my $count = 0;
$callback = sub {
# Creates a closure
print ++$count, ": $File::Find::name\n";
#$count has a refcount of 2
}
}
#$count has a refcount of 1, so its still around
find ($callback, ".");
The above can be implemented with state in modern 5.010+ without the extra scope block.
---------------------------
Return a closure
---------------------------
use File::Find;
sub create_find_counter {
my $count = 0;
return sub {
print ++$count, ": $File::Find::name\n";
}
}
my $callback1 = create_find_counter();
my $callback2 = create_find_counter();
each have an independent count.
--------------------------------
Shared variables among closures
--------------------------------
use File::Find;
sub find_callback_and_report() {
my ($total_files, $total_bytes) = (0,0);
my $calc = sub {
return if -l or not -f _; # Not a link or not a file
$total_files++;
$total_bytes += -s _;
};
my $report = sub {
print "Total: $total_bytes bytes in $total_files files.\n";
}
);
my ($calc, $report) = find_callback_and_report();
find($calc, ".");
find($calc, "./ab");
find($calc, "./ac");
$report->();
-----------------------------
File::Find::Closures
-----------------------------
-----------------------------
state variables
-----------------------------
use 5.010; or use v5.10;
-----------------------------
END blocks
-----------------------------
BEGIN blocks execute top to bottom
END blocks execute bottom to top
only run if running is normal, not for crashes.
Cool new feature in perl 6:
$begin <= $m >= $end
Can we port this???
-------------------------------
Filehandle and Regex References
-------------------------------
open my $fh, "..." or die "???: $!";
while (<$fh>) {
print "One entry"
}
another way
open my $fh, '>>', 'xxx.txt' or die "$!";
print_to_this($fh);
sub print_to_this {
my $fh = shift;
print $fh "Ayyy";
}
also:
print {$fh} "xxx\n"; # helps clairify the distinction of a fh.
the above are required if the file handle is stored in anything but the scalar.
print {$array[0]}, "xxx\n";
--------------------
many files at once
--------------------
foreach my $file (glob "*.in") {
(my $out = $file) =~ s/\.in$/.out/;
open my $input...
open my $output...
push @handle_pairs, [$input, $output];
}
while (@handle_pairs) {
@handle_pairs = grep {
if (defined(my $line = readline($_->[0]))) {
print { $_->[1]} $line;
}
else {
0;
}
} @handle_pairs;
}
as the file handles go out of scope, they are automatically closed.
This seems pretty obscure syntax for this process.
---------------------
Specialized handles
---------------------
---------------------
File handles on scalars
---------------------
open my $fh, ">", \ my $string;
print $fh "Foo";
Books:
* Effective Perl Programming
* Network Programmin in Perl
---------------------
Regexs, old way
---------------------
my $what = 'Gill.*n';
if (/$what/) {
}
These cost a lot since they are recompiled all the time.
Better to compile once.
---------------------
Refernce to Regex
---------------------
my $regex = qr/Gill.*n/; #Compiles
ASSIDE: Shows the code that perl thinks it has
perl -MO=Deparse -e '@$^R;';
-----------------------
Practical Ref Tricks
-----------------------
# Step 1, cache the file and size in array.
my @files = glob "*";
my @files_and_sizes = map [ $_, -s ], @files;
# Sort by size
my @sorted_refs = sort {
$b->[1] <=> $a->[1]
} @ files_and_sizes;
my @sorted_files = map $_->[0] @sorted_refs;
--------------------------
The Schwartzian Transform
--------------------------
Randel Schwartz
my @sorted_files =
map $_->[0],
sort { $b->[1] <=> $a->[1] }
map [$_, -s],
glob "*";
# Same results as above without all the intermediate variables
----------------------------
Recursive Data Structures
----------------------------
$homedir = &gather("/home");
sub gather {
my $dir = shift;
opendir GATHER, $dir or return;
my @kids = readdir GATHER;
my %self;
foreach my $kid (@kids) {
next if $kid eq "." or $kid eq "..";
$self{$kid} = &gather("$dir/$kid");
}
return \%self;
}
#works
now lets play with the data structure:
sub display {
my ($label, $node) = @_;
if (not $node) {
print "$label\n";
}
elsif (my @contents = keys %$node) {
print "$label, with contetns of:\n";
...
}
else {
}
}
#OK, but ugg.
Some compilers can optimize this to remove the recursion... TelCall optimization not available in perl since we can redefine stuff (Dynamic Language)
How do we convert this to an iterative solution?
my @queue = ( ["/home", {}] );
while( $e = shift @queue ) {
opendir /home
---> keys
push @queue [ $key, $e->[1]];
}
# Nice thing is we can push, unshift or insert so we can control depth first, breadth first or other.... we can skip things, we can trim at a certain depth...
www.perlmonks.org/?node_id=393128
playing with dumbbench
http://www.masteringperl.org/2013/02/playing-with-dumbbench/
-----------------------------
Libraries and Packages
-----------------------------
require - loads a file, checked its cache first, if it doesn't work, it dies.
looks for a true value for the last statement to be true.
1; # at the end of the file
How to find the library?
* Full path.
* Partial path from root. (Searches @INC list)
*
perl -V - shows all the global variables
ways to change the @INC list:
setenv PERL5LIB ...
PERL5LIB=...; export PERL5LIB;
perl -I "path"
----------------------------
Namespace collision
----------------------------
last definition wins.
with perl 5 adds packages.
----------------------------
Declaring shared package variables??? (old way)
----------------------------
package a;
use vars qw/ @labels @sizes @garmennts /;
----------------------------
Declaring shared package variables??? (new way)
----------------------------
package a;
our ($a, $b, $c);
How to get the package information.
$package=__PACKAGE__;
($package, $file, $line) = caller(o);
-----------------------
Object Oriented Perl
-----------------------
sub Cow::speak {};
sub Horse::speak {};
sub Sheep::speak {};
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
&{ $beast . "::speak"};
}
# doesnt work in strict
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
$beast->speak();
}
# this is strict safe
--------------------------
Class->method(@args) => Class::method("Class", @args)
--------------------------
{
package Cow;
sub sound { "moooo" };
sub speak {
my $class = shift;
print "a $class goes", $class->sound, "!\n";
}
}
{
package Sheep;
...
}
{
package Horse;
....
}
---------------------
the speak sub routine is now generic.
{
package Animal;
sub speak {
my $class = shift;
print "a $class goes", $class->sound, "!\n";
}
}
{
package Cow;
@ISA = qw(Animal); # Parent class
sub sound { "moooooo" };
}
# Pretty simple.
How does it work?
Cow->speak
Cow::speak ??? no
Looks in parent packages
Animal::speak ??? yes
&Animal::speak("Cow", @args);
Same process is used for the sound() method called by speak().
1) Look in current package
2) Look in each class defined in @ISA.
------------------
Specialization
------------------
{
package Mouse;
@ISA = qw(Animal);
sub sound { "squeak" };
sub speak {
my $class = shift;
$class->SUPER::speak; # Calls the parent class
print "[but you can barely hear it!]\n";
}
}
-------------------
Bless
-------------------
Turns a reference into an object.
my $name = "Mr. Ed";
my $talking = \$name;
bless $talking, "Horse";
$talking is a Horse now...
print $talking->speak(), "\n";
results in:
Horse->speak($talking);
-------------------
{
package Horse;
sub name {
my $self = shift;
$$self;
}
}
--------------------
Constructors
--------------------
Name of constructor can be anything. More like a factory method.
{
package Horse;
sub named {
# Im the constructor...
my $class = shift;
my $name = shift;
bless \$name, $class;
}
}
my $talking = Horse->named("Mr. Ed");
print $talking->name, " says ", $talking->sound, "!\n";
>> Mr. Ed says neigh!
Raymond Shen (Microsoft win32 guy)
---------------------
{
package Animal;
sub speak {
my $either = shift; # Class or Instance
print $either->name, " says ", $either->sound, "!\n"
}
sub name {
my $either = shift;
ref $either ? $$either : "Unnamed";
}
}
-----------------------
now lets make them eat.
{
pacakge Animal;
sub eat {