-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNOTES.txt
991 lines (669 loc) · 29.6 KB
/
NOTES.txt
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
PERL PERL PERL NOTEPAD
Learn Perl:
========== 2/17: https://www.youtube.com/watch?v=iEOXOQE20SU =======
Scalar = either numbers or strings (comes from Awk)!
numbers are always floating point.
Represented sanely
Numbers can be non-decimal
0777 0xFEEDBEEF
Strings:
Sequence of chars (any bytes any length)
String literal, can be single suoted
'foo' 'longer string' 'don\'t leave home without it.
"\" takes away property. Takes away string power.
single quoted string
variable stays in place. Pretty much as is, wysiwyg
double quoted string " " more power. Get backslash escapes bv: print "hello\n";
- interpolate variables
String operator
concatonation
ex: 'fred'.' '.'Flinstone'
Replication:
'hello' x 3
'hello x 3.5
scalar conversion
13 + 5 . 'Monkeys
strings can be used as numbers:
String to number conversion
'12' / 3 = works
'12fred' / 3 = turns in number trailing non number scrap becomes number
'fred' / 3 = 0
'12fred23 = perl ignores 23.
-Warnings:
#! /usr.perl + "-W" option
"use diagnostics;" after warnings errors that come up will look it self up in the perl documentation
Scalar variable in Perl:
dollar sign one or more letters digits underscors
ex: $a $1 $_
variables are case sensitive
lowercase for locals, captial for globals
perl doesn't care just a convention
Typically get value through assignment:
$a = 3;
$b = $a + 2;
$b = $b * 4; same as "$b *=4" => combination assignment operators shortcut
-Simple output:
Double quoted interpolation:
$x = 3 + 4;
print "hello, the answer is ", $x, "\n";
Single quoted strings don't understand newline, \n
Comparison operators combination
numeric Comparison
== != < > <= >=
string Comparison
eq, equal ne, not equal lt, less than gt, greater than, le, less or equal to ge, greater or equal to
--Use math symbols when dealing with numbers use words when dealing with words
Simple "If"
Choice based on comparison
if ($x > 3) {print "x is greater\n"}, else { print "x is less than or equal to 3\n"; }
else is optional, usage of if is enough.
Braces are required ( r called blocks)
Boolean logical
Comparison can be stored
$is_bigger = $x > 3;
if ($is_bigger) {...}
Whats in $in_bigger? "true " or "false"
false: 0, empty string '0' or undef
Simple USer input
$x = <STDIN>; line input function. Whatever you type in goes in to $x.
CHOMP: get rid of new line
chomp($x);
Typical they will be combined
chomp($x = <STDIN> ); "()" are needed on this.
- Simple loops
$c = 0;
while ($c <10) { $c +=2; print "count is now $c\n" #gives 2 4 6 8 10 }
test
-- perl -Mstrict -We 'my $count = 0; while ($count <10) { $count +=2; print "The count is now $count\n"}' --
CPU TESTER: perl -Mstrict -We 'my $count = 0; while ($count <10) { $count -=2+31+3+4*44.3/4,2+4502*32,44**57739,44,444/23555,4/44**87666,744492999*222234444+57777777**989,8885843422**8,999999993; print "The count is now $count\n"}'
- The Undef Value
Initial value for all Variables
treated like 0 for math
Is it really undef or is it just 0 in an empty string
Detect undef with defined()
===========PART 3 / 17 LIST AND ARRAYS: https://www.youtube.com/watch?v=ClqY8cGa1q0&spfreload=5
$fred[0] = "yabba";
$fred[1] = "dabba";
$fred[2] = "doo";
- This is the fred array, not the scalar fred, they both begin with dollar sign,
- you have to look at the entire syntax as a unit. When perl sees fred[] It knows that it's the fred array
Subscript expression can be any integer-yielding value:
$n = 2;
print $fred[$n]; #will print $fred[2]
print $fred[$n / 3]; #truncates 2/3 to 0, thus $fred[0];
Maximum element index available:
$max = $#fred; #$max = 2
$last = $fred[$#fred]; #always last element
out-of-bounds subscripts return undef:
defined $fred[17]; #false, returns undef
assign beyond end of array just stretches it:
$fred[17] = "hello";
It's basic structure of an array we can access we can increase the size, we can access counting upward of downward.
----List Literals:-----
List of Scalars, seperated by commas, enclosed in parens:
(1,2,3) same as (1,2,3,) # trailing comma, doesn't change symantics at all.
("fred", 4.5) #
()#empty list
(1..100) #same as (1,2,3,... up to ...,98,99,100) - ".." is an operator in perl(5). Generator values from 1 to a 100
- ".." runs at runtime, not fixed to compile time
(0..$#fred) #all indices alle indexen
Quoted Words:
qw(fred barney betty wilma) #same as ("fred","barney","betty","wilma") without having to type all those quotes and commas
#white space is arbitrary
qw[fred barney betty wilma] qw[ ] or qw<>
works with paired delimters
or duplicate non paired delimeters
qw|foo bar|
List literal can be handed directly to "print"
You can assign them to another list
--List assignment:--
corresponding values are copied:
($fred, $barney, $dino) = ("Flinstone","ruble",undef); #extra values automatically get undef,
too short on the right ? extras get undef:
($fred, $barneby, $dino) = qw(flinstone rubble);
too short on the left? extras are ignored
"=" the equel sign in this context becomes a list assignment operator, because There is a list on the left hand side.
--"All Of the shortcut"---
image assigning the consecutive array elements:
($rock[0], $rock[1],$rock[2],$rock[3]) = qw (talc mica feldspar quartz);
simpler: "all of the"
@rocks = (talc mica feldspare quartz);
Previous value is always completely erased
can also be used on right side of assignment:
($a,$b,$c,$d) = @rocks
@his_rocks = @rocks;
@her_rocks = ("diamond", @rocks,"emerald");
--Array Operations--
Remove end of array:
@numbers = (1..10);
$final = pop @numbers; #final gets 10 #pop argument takes an array removes its final element, and returns that value.
Adding items to end of array:
push @numbers, 10..15; #Push adds numbers to the end of an array, (it is a destructive method, changing the array)
add to beginning of array:
unshift @numbers, -10..0; #it works by sliding indexes in the array over to the left
Remove from beginning of array:
$minus_ten = shift @numbers; #pulls first element of the array/list
---Array interpolation
Single elements act like Scalars
@rocks = qw(flinstone slate rubble);
print "barney $rocks[2]\n"; #barney rubble\n
"all of the" inserts spaces:
print "got @rocks\n"; #got flinstone slate rubble\n
beware email addresses in double quotes:
print "my email address is [email protected]\n"
precede @ sign with \ to avoid interpolation # or put the email address in single quotes '[email protected]';
#or "merlyn\@stonehenge.com";
--Using Foreach--
Simplest way to walk a list:
foreach $rock (qw(bedrock slate lave)) { print "one rock is $rock\n;}
perl -Mstrict -wE 'foreach my $rock (qw(bedrock slate lava)) {print "one rock is $rock\n";}'
$rock is set to each elmeent in the list in turns
any outer $rock is unnafected
Assigning to $rock affects the element.
@rocks = qw(bedrock slate lava);
foreach $rock (@rocks) {$rock = "hard $rock"}
leaving variable off uses $_
foreach (@rock) {$_ = "hard $_"} # leaving the variable of foreach, perl presumes the variable $_
# $_ is like any other scalar, perl defaults to $_ for a lot of Operations
--- List Operations ---
--reverse:
@rocks = qw(bedrock slate rubble granite);
@reversed = reverse @rocks;
@rocks = reverse @rocks;
reverse is nog destructive, it is taking a copy of the list and reversing that in memory and resulting that as the list
It does not make sense to type "reverse @rocks", we told perl to make a copy of the list so we can reverse it and then throw that away.
Therefore @rocks = reverse @rocks;
Otherwise warnings will come up ex: void context, use of reverse
--Sort (stringwise):
default string sorting in alphabetical order (ASCII order)
@rocks = sort @rock;
@rocks = reverse sort @rocks;
again sort is like reverse, it is not destructive
Reverse sort:
Perl recongnises the special sequence "reverse sort", will take the copy of the list and reverse the list, in descending order
instead of ascending order. Perl doesn't bother with the intermediate step, it doesn't make 2 copies of the list.
(1 for "reverse" and 1 for "sort"), it sends a flag to the start routine to say, sort descending rather than ascending.
again "sort reverse @_" would be pointless and wasting CPU time
Default sort is not numeric:
@result = sort 97..102, #100, 101, 102, 97, 98, 99
---Scalar and List and context
--Important to recognize when Perl needs which:
43 + Something # looking for a scalar, or evaluated in a scaler context
sort something # looking for a list, sorting something is probably going to sort a list, so evaluating sort in a list context
All operators provide a very well known context to all of their operands.
...because some things return different values
@people = qw(fred barney betty);
@sorted = sort @people; #@people returns elements
$number = 42 + @people; #@people returns 3 (count) using list context in a scalar context returns the number of items i/t array
--Even assignment itself has context:
@copy = @people; #list assignment (elements) copying people list into copy list
$count = @people; #scalar assignment(count) scalar on the left hand sign, will copy the number of list items into $count
---List context <STDIN>
--scalar context: one line at a time, undef at EOF
--List context: all remaining lines:
@lines = <STDIN>; #entered lines, returns all entered lines, 4 ex: 47 lines waiting to be read, you get 47 seperate elements in @lines
#all of them will have "\n" new line operators on the end, CHOMP to get rid of them ?
#
kill those newlines:
chomp(@lines = <STDIN>);
reading input from the terminal it will read the input untill "terminal end of file,(EOF)" unix, -> CTRL + D to send EOF input.
<STDIN> notice it is the same syntax as for scalar context of list context, we get related operations, read one line read all the lines
<STDIN> be aware it does bring the entire list into memory, not a good idea to read big files.
===========PART 4 / 17 Subroutins / Functions: https://www.youtube.com/watch?v=JQ8MLq_Bfpo ====
Subroutines: Define subroutine, chunk of code that has a name that you can invoke from somewhere else in the program.
Define with keyword "sub":
sub marine {
$n += 1; #global dollar N increment by 1 -> +=
print "hello sailer number $n!\n";
}
Invoke in an expression with & in front of name:
&marine; # Hello sailor number 1
&marine; # Hello sailer number 2
--Last expression evaluated is return value:
Return value: What ever the last expression evaluated in the subroutine is also automatically returned back as the return value
for the subroutine
sub add_a_to_b {
print "hey, I was invoked!\n':
$a + $b;
}
$a = 3; $b = 4; $c = &add_a_to_b;
#output will print return 7.
#When inverting the two statements in the subroutine; I would a to b = 7 would be just thrown away, because the Last
#thing is print. Print has a return value, so the return value would return true or false.
sub add_a_to_b {
$a + $b;
print "hey, I was invoked!\n':
}
--Not Necessarily textually last:
#The last expression evaluated is not necessary what's on the last line of the subroutine,
#We could have control structures, loops etc , so it's whatever we get to last at runtime.
sub bigger_of_a_or_b {
if ($a > $b) {$a} else {$b} #assign value to a assign a value to b and call subroutine and subroutine is going to call the
} #and the subroutine is going to return the larger of the two.
#and it does it by if a is greater than b, mathematically or numerically, can we evaluate $a
#it doesnt change $a, but it makes it the last value evaluated, so that's going to be the return value
#now if we go of to the "else" branch instead because a is less or equal to b, then we get b evaluated
#which makes IT the larger of the two.
Whatever is evaluated last at runtime, is also automatically the return value of the subroutine
---Arguments
--Values passed in parens get assigned to @_
$n = &max(10,15); #Arguments being passed in to the subroutine.
sub max {
if ($_[0] > $_[1]) {$_[0]} else {$_[1]} # 10 will become $_[0] 15 will become $_[1]
}
#
--Note that @_ has nothing to do with $_
#Whatever list of values gets passed in gets assigned to @_
--@_ is local to the subroutine.
If subroutine would be calling another subroutine, it would be gettings it's own @_ (underscore array) etc.
It even works recursively, if subroutine calls itself, each new invokation layer gets a new @_.
--Perl doesn't care if you pass too many of too few.
If more elements are passed than referenced, it will ignore the extra indices. Under the condition of 1 element(10, ),
will return undef. And would be warnable.
---Creating Local Sub variables ---
--Use "my" to create your own local vars
sub max {
my ($x, $y);
($x,$y) = @_; #copy arguments to $x, $y
if ($x > $y) {$x} else {$y}
}
-- Variables declared in my() are local to block
-- Steps can be combined
my($x,$y) = @_;
-- Typical first line of a subroutine
-- Or maybe;
my $x = shift, my $y = shift; #shift will take the first argument in the list and throw it in $x
#(shifting empty array not warnable offence)
#
example: my $x = shift if @_ # if is looking for true or false value, if @_, would look for empty or not array.
---Variable Arg List
What if I want &max to a variable number of arguments
--Just respond to all of @_;
(2,10,3)
sub max {
my $best = shift; #shifting off the first parameter, 2, goes to $best, foreach is going to go over it twice, first, $next = 10, we check if $next is greater than current item we have,(best, 2).
foreach $next (@_){ #if it's better(larger), we keep it.
if ($next > $best) {$best = $next} #foreach loop is empty,
}
$best;
}
Now it works for 15 args, 2 args, 1 args, even 0 args!
--- "my" not just for subs ---
-- lexical vars (introduced with my()) works in any block
foreach (1..10) {
my $square = $_ * $_;
print "$_ squared is $square\n";
}
--- "Use Strict" ---
Ensure declared variable names:
use strict; # at top of file
--Now all user-defined vars must be "introduced"
my $x = 3;
$x; #ok
$y; #not ok.. no "my" in scoped
{
my $z;
$z; #ok
}
$z; # not ok (out of scope)
--- Early Subroutine Exit ---
--Break out of a subroutine with "return"
--sets the return value as a side effect
my @names = qw(fred barneby betty dino wilma);
my @result = &which_element_is("dino",@names);
sub which_element_is {
my($what, @array) = @_;
foreach (0..$#array){ #indices of @array's elements
if ($what eq $array[$_]{return $_}
}
-1; #not found
}
# Most legacy code has no explicit returns
#
state introduced in 5.10
====Persistent but local ===
--- Back to first exmple
sub marine {
state $n = 0; #initial value
$n += 1;
print "Hello, sailor number $n!\n";
}
========= Input and Output (05/17) - https://www.youtube.com/watch?v=iPtU8VWxiq8 ====
=== Reading to EOF ===
--Reading a line:
chomp(my $line = <STDIN>);
--Reading all lines, one at a time: #
while (defined(my $line = <STDIN>)){ # assigning the line input operator assigning it to $line (introducing variable with "my") #defined
do something with $line; # return value of the line input operator is that, next line can be read or undef if we have end of file.
} # defined function is evaluating the result of that assignment to see whether it's undef or not.
# while will keep going if there are lines, don't keep going if there is none.
--shortcut for defined($_ =<STDIN>)
while (<STDIN>) {...}
-- Very common thing to do.--
--Don't confuse with:
foreach (<STDIN>)
---Filters
--Act like a unix Filter
-read from files named on command line
-write to standard output
-any "-" arg, or no args at all:read standard input
-- Perl uses <> (diamond) for this:
while (<>) {
#one line is in $_
}
--Invoke like a filter:
./myprogram fred barney betty
--- @ARGV
--Really a two step process
- Args copied into @ARGV at startuo
- <> looks at current @ARGV
--Common to alter @ARGV before diamond:
if ($ARGV[0] eq "-v"){
$verbose = l; shift; #inside subroutine shift shifts $_ outside subroutine, shift shifts @ARGV array
}
while (<>) {...} #now process lines
--- Formatting Output ---
--Use printf:
--printf "hello %s, your password expires in %d days!\n",
$user, $expires;
==========Numerical values / Numerieke waarden===== https://perlmaven.com/numerical-operators
say 2 + 3; # 5
say 2 * 3; # 6
say 9 - 5; # 4
say 8 / 2; # 4
say 8 / 3; # 2.66666666666667
# Note that Perl will automatically switch to floating point number when necessary so when we divide 8 by 3 we get a floating point value.
say 9 % 2; # 1
say 9 % 5; # 4
my $x = 2;
my $y = 3;
say $x + $y; # 5
say $x / $y; # 0.666666666666667
-------Shorthand operators---
The expression $x += 3; is the shorthand version of $x = $x + 3;, they have exactly the same result:
my $x = 2;
say $x; # 2
$x = $x + 3;
say $x; # 5
my $y = 2;
say $y; # 2
$y += 3;
say $y; # 5
#In the general case VARIABLE OP= EXPRESSION is the same as VARIABLE = VARIABLE OP EXPRESSION, but usually easier to read and less error-prone.
#(We don't repeat the name of VARIABLE.) You can use it with any binary operator:
#+=, *=, -=, /=, even %=
-----Auto increment and auto decrement----
#Perl also provides ++ the auto increment, and -- auto decrement operators.
#They increase and decrease respectively the value of a scalar variable by 1.
my $x = 2;
say $x; # 2
$x++;
say $x; # 3
$x--;
say $x; # 2
#Both the postfix versions $x++, $x-- and the prefix versions ++$x, --$x and they behave the same way as in other languages.
#In case you are not familiar with them, then this is not the time to become deeply acquainted with them.
#They can be used as part of a larger expression when being pre-fix or post-fix really matters, but in most cases I think the best is to avoid such expressions.
#They can be fun and a maintenance nightmare. We'll have an article explaining short-circuit and the pitfalls of auto increment with short-circuit.
----Communicatieve bewerkingen-----
|
|
bv: 2 + 3*4 = 14 : correct mathematische volgorde ( eerst *)
Geforceerde mathematische volgorde
bv: (2+3)*4 = 20
Comparison Operators
< <= == >= > !=
Comparison - Numeric - String
equal == eq
Not equal != ne
Less than < =lt
Greater Than > = gt
Less than or equal to <= le
Greater than or equal to >= ge
user input
$line = <STDIN>;
if ($line eq "\n") {
print "That was just a blank line!\n";
} else {
print "That line of input was: $line";
}
???---------------------------------
undef P40
./Build && ./Build install && dhconveyor transport -p testit.ini -L 3
------------------------------------------------------------------------------------------
ListEn Arrays
Meerder waarden in variabele:
List and arrays
List = Data & Array = Variabele
You can have a list variable that isn't an array but every array variable holds a list (although that list may be empty)
Your next step could be to write a program, and then wehn you get stuck, post a question in SoPW. See SSCCE. (1) This is what I tried; (2) This is is what it produces; (3) This is what I want to happen; (4) Help please?
use 5.18.0 = Use version of perl always in strict mode = "use strict;"
$x = $x + 100; same thing as $x += 100;;
Whiespace and comments
Whitespace = space characters, tab characters, - mostly ignored.
except ex. "sub main" ! "submain" needs white spae
{ } around var = clearly var even without whitespace
Comment to make src code more readable
sub main
{ #accolades better idea of placement because more clear
my $filename = shift || "linesfile.txt";
my $count = countlines ( $filename );
}
blocks are defined by { }
vars inside block override variable outside block.
vars outside block cannot reach var declaration inside block. par ex.
my $x = 1; my $x = 1;
if ($x) { if ($x) {
my $y = 2; not my $y = 2;
say $y; }
} say $y
output: Global symbol "$y" requires explicit package name...................
Variable is symply a names container for values.
var name can be any set of characters
3 Perl storage types:
scalar, holds a single value
SCALAR variable= SCALAR with $
ARRAY holds series of values = @array = extracting the value will output same order of entered values
%HASH, holds a set of key/value pairs.
Perl references,
A SCALAR that refers to another object
$x = <STDIN>;
print $x;
Numeric Variables:
Assign number to var,
my $n = 42;
$n = $n * 2;
print "n is $n";
output will be:
n is 84
[ ] around print variable will show where the var starts in output (shows where the boundries of the string are)
par ex.
"print "n is [$n]";
String Value in Perl:
par ex.
my $s = "Hello world";
print "s is [$s]";
my $s = "Hello world";
$s = $s . " This is a string. "; ##### concatonation operator "." added one string on top of another.
print "s is [$s]";
string interpolation when you have a var inside of the string and that var is expanded inside of the string.
my $s = "Hello world";
$s = "This is a string. $s this is another string.";
print "s is [ $s]";
To expand variable.
my $s = "Hello world";
$s = "This is a string. ${s} this is another string.";
print "s is [ $s]";
escaping
if you want quote marks use = \"content"\ display " as quote marks not as syntax
\\ = \ single backslash
qq( content ) = interpolation quote operator -
--------------------------------------------------------------------
_______________________Logical values_______________________________
Are used in conditionals and loops
my $x = 1;
my $y = 1;
if ( $x == $y ) {
say 'true';
} else {
say 'false';
}
if statement takes a logical value to decide which block of code will be executed
== : tests for equality
Lists and Arrays
List, a fixed series of scalar values
print foreach (1, 2, 3);
out will be:
1
2
3
qw = quote word operator, create list of strings.
par ex.
print qw( one two three )[1]
@array, is a variable data structure that holds a series of scalar values.
my @array = (1, 2, 3); ## creates an array with the @ sympbol introducing the array ######variable. and it initialises the array from a list. 1, 2, 3 is a list of integer values. That's being used to initialise the array named @array
my @array = (1, 2, 3)
say foreach @array;
Individual element of array can be specified with a subscript.
print $array[0]; prints individual value of array
print $array[2];
---------------------------------------------------------------
_________________SLICES:_______________________________________
my @array = qw( one two three four five six seven eight nine ten );
say foreach @array;
print $array[3] will return one value
print @array[1,2,3]; will return list of values. or individual values
to specify range of indices.
print @array[1..5] output will be list values from 1 to 6
because slice returns a list we can initialise another array with it.
for ex:
indexes: 0 1 2 3 4 5 6 7 8 9
my @array = qw ( one two three four five six seven eight nine ten);
my $a2 = @array[5,7,2,9];
say foreach @a2;
output will be:
six
eight
three
ten
----------------------------------------------------------
___________________________HASH___________________________
hashes special kind of arrays that associates keys and values
my %hash = ( one => 'uno', two => 'dos', three => 'tres', four => 'quatro', five => 'cinco' );
while( my ($k, $v) = each %hash ) {
say "$k -> $v";
}
-------------------------------------------------------
_____________________SUBROUTINE/FUNCTION______________
# \/
# ||
# ||
#do not put a fucking semi\/ colon here or shit goes haywire !
sub sum_of_fred_and_barney #expression containing the invocation "&"
{
print "Hey, you called the sum_of_fred_and_barney subroutine!\n";
$fred + $barney; #That's the return value #with addition of "print" $fred + $barney not return value
# print "Hey, I'm returing a value from!\n"; #oops #Not the addition anymore; it's now the print statement
#whose return value is normally 1, meaning "printing was succesful"
#not the return value requested, be carefull adding additional code
#to a subroutine, since the last expression evaluated will be the return value
#a failure would result in return value of 0 or (false?)
}
$fred = 3;
$barney = 4;
$wilma = &sum_of_fred_and_barney; # wilma gets 7 because we asked for wilma to become the sum of fred = 3 and barney = 4 wich is 7
#&sum_of_fred_and_barney calculates the value of the expression containing the invocation.
print "\$wilma is $wilma.\n";
$betty = 3 * &sum_of_fred_and_barney; # betty gets 21 because we asked for betty to become the sum of fred = 3 and barney = 4 which is 7 times 3...
# ...wich is 21
# betty does everything times 3 because $betty = 3 * x?
print "\$betty is $betty.\n";
$dino = 5 * &sum_of_fred_and_barney;
print "\$dino is $dino.\n";
#warning void context is just a fancy way of saying that you aren't using the answer,
#whether that means storing it in a variable or using it any other way.
hello();
sub hello
{
say "This is the hello function.';
}
##################### Lexical Scoping ##########################
#my variable inside the fucntion, "my" keyword creates variable with local scope.
#$x inside function is used inside function block
#local variables will allways take precedent over outside variables
#The variable is private to the enclosing block; in this case, that's the block
#of the foreach loop. If There's no enclosing block, the variable is private to the entire source file.
my $fred, $barney; #Wrong, fails to declare $barney
my($fred, $barney); #declares both
#return values can return 0's or more scalar values as a list
#
#Returning values #return #subroutines #functions
# print func();
# sub func
# {
# return 'This is a wonderful function.';
# }
# --------------Using return to get list values-----------------
# print foreach func(). "\n";
# sub func
# {
# return ( 1, 2, 3, 4, 5 );
# }
# -------------Printing with each list element on new line------------------
# print qq($_\n) foreach func();
# sub func
# {
# return ( 1, 2, 3, 4, 5 );
# }
# -------------------- Static Variables -----------
# func();
# func();
# func();
# func();
# func();
# func();
# sub func
# {
# my $n = 10; #n w. 10
# print ++$n; #increment $n 10 w. 11 en print
# }
# Static variable Example:
# func();
# func();
# func();
# func();
# func();
# func();
# sub func
# {
# state $n = 10; #state counts with increment of 1 gebruikt "use feature 'state'; bovenaan
# print ++$n; #increment $n + 1 x aantal "func ();" = 11 12 13 14 15
# }
# --------- Predeclared Functions ---------
#func (); gebruiken op functie te invoken werkt niet met "func;" -> geeft error
#om functie te gebruiken zoals de predeclared -> use subs qw ( "chooseurself"* );
#Meer om het gebruiksgemak van functies te verhogen. En ze gemakkelijker aan te roepen.
use subs qw( func );
func 'Foo', 'bar', 'baz';
sub func
{
print foreach @_ ;
}
========== :: Omitting The Ampersand :: ========
"If perl can see that it's a subroutine call without the ampersad from the syntax alone, that's generally fine
That is if you've got he parameter list in parenthesis, it's got to be a function call"
ex: my @cards = shuffle(@deck_of_cards); #no & necessary on &shuffle
sub division
{
$_[0] / $_[1];
}
my $quotient = division 355, 133;
This works because of the rule that you may always omit parenthesis when you don't change the meaning of the code. You can't omit those parentheses if you use te & though.
Don't put the subroutine declaration afther the invocation; if you do, the compiler won't know what the attempted invocation
of division is all about The compiler has to see the definition before the invocation in order to use the subroutine
call as if it were a built-in. Otherwise the compiler doesn't know what to do with that expression because
it doesn't know what C divisiion > is yet.
======================= Persistent Private Variables ==============
my var = ability to make private variables to the subroutine.
Each time you called the subroutine you had to define them again.
State = still private variables scoped to the subroutine Perl keep their values between calls