My summary of Perl in semester 16s2 of (COMP2041|COMP9041) in UNSW.
My note of lectures, it was a mess and not well organized.
So I decided to write this blog to make things clear(I need time to modify).
Perl = Practical Extraction and Report Language
Running Perl code in the command line
perl -e ’print "Hello, world\n";
#!/usr/bin/perl -w
Adding this line at the beginning of the file, which will let the operating system know that this file is Perl program so that it can be executed in this way:chmod 755 PerlCodeFile;./PerlCodeFile.pl
-w
means warnings.
Arithmetic & Logical Operators
Numeric: == != < <= > >= <=>
String: eq ne lt le gt ge cmp
Input/Output
Andrew always gives us advice to make our life easier, and one thing is always remembering to check the file is correctly opened.
Elegant usage of die:
1 | # $0 is the perl filename, and $! is the error msg. |
Sample implementation of cat
1 | while ($line = <STDIN>){ |
read, write and append
1 | open(DATA, "<< data"); # read from file "data" |
Read content of web page through url:
1 | open F, "wget -q -O- $url|" or die; |
Saving lines of file content to array
1 | @lines = <STDIN>; |
Control Structures
For loop
1 | foreach $arg (@ARGV){} |
If
Testing the line's content, =~
is so useful in perl.
1 | if ($line =~ /($course_prefix[0-9]{4})<\/a>/){ |
Data structure
String:
1 | # "Henry\n" --> "Henry" |
split a string:
1 | @field = split /,/, $line; |
Array
1 | $a[4] = 42; # @a = (,,,,42) |
Hash
Here is a useful example from my lab code:
we can also see how sed work in perl:
1 | foreach $input (sort keys %total_p_of){ |
SHELL Command in Perl
Perl is shell-like in the ease of invoking other commands/programs.
Several ways of interacting with external commands/programs:
1 | `cmd`; # capture entire output of cmd as single string |
Reference
This exaple explains this concept so well:
1 | $henry = 42; |
Math
Square root: sqrt $x*$x + $y*$y
Calculation of string:
1 | $string = "1+2+3+4+5"; |