Perl
Perl Character
1. Easy for use
2. Can do everything
3. Run quite fast
4. Code hard for reading
Perl Suitable Area
1. 90% file process; 10% others process;
2. Write CGI script;
Support website
CPAN: https://search.cpan.org
Install Perl
1. Download package
2. Install package
3. set path parameter by adding C:\Perl\bin;
4. create one test file test.pl with
print "Hello World"
5. in command windows input: perl test.pl
Integrate into Eclipse
1. install EPIC package
2. Install PadWalker package
Example
$a="Hello World";
print $a;
Format
if (...)
{...}
else if (...)
{...}
else
{...}
while (...)
{...}
Number
1. Standard Variables including Integer / Variable / String
2. use float to save all number
3. support: +, -, *, /, %(Remainder 8%5=3), **(Exponentiation 2**3=8)
4. write Bin: 0b11111111
5. write Oct: 0377
6. write Hex: 0xff
String
1. no limit to string, can be empty or as long as possible
2. support unicode: use utf8
3. use '' or "" to indicate string
A. '\n' --> \n
B. "\n" --> enter
4. connect two string using .
"hello"."world" --> helloworld
5. repeat string using x<number>
"hello"x3 --> hellohellohello
Variable: $<variable name>
Variable name: distinguish upper and lower
Variable name: can not contain space
$abc=1
print "$abc"-->1
print "\$abc"--> $abc
Compare: ==(eq), !=(ne), <(lt), >(gt), <=(le), >=(ge)
declare variable with out set, the value of variable will be undef
when the variable used as number, undef as 0
when the variable used as string, undef as null
Perl do not have boolean
null / 0 / undef works as false, other works as true;
Function
1. defined: check variable as undef or not
$ma=<STDIN>;
if (defined($ma))
{print "The input is $ma."; }
else
{print "It is undef"; }
input Ctrl + z to finish the input
2. chomp: remove the enter at the end of input
chomp ($ma=<STDIN>);
List
List: list of data
(1,2,3), (1..5)
($a,$b,$c)=('a',4.5,undef)
Array
Array: list of variable @<variable name>
@ma
$ma[0]="a"; $ma[1]="b"; $ma[2]="c";
if input $ma[99]="d", from 3 ~ 98 value is undef
index of array: start with 0,1,2,....
index of end of array with minus -1,-2....
get length of array: $#ma
@a=((1,2,3),"hello",undef);
print @a;
--> 1 2 3 hello
Array operation
1. pop: get the last item of array, and array remove the last item
@array=1..5;
$a=pop(@array); --> $a=5, @array=(1,2,3,4)
2. push: add item to the end of array
@array=1..5;
push(@array,6) --> @array=(1,2,3,4,5,6)
3. shift: get the first item of array, and array remove the first item
@array=1..5;
$a=shift(@array); --> $a=1, @array=(2,3,4,5)
4. unshift: add item to the start of array
@array=1..5;
unshift(@array,6); --> @array=(6,1,2,3,4,5)
5. splice: add or remove item in the middle of array
splice(array, start position, end position, replace list)
@array=1..5
@remove=splice(@array,1,2); --> @remove=(2,3) @array=(1,4,5)
@array=1..5
@remove=splice(@array,1,2, qw(6,7)); --> @remove=(2,3) @array=(1,6,7,4,5)
6. foreach: visit the items of array
foreach $rock(qw/bedrock slate lava/)
{print "One rock is $rock\n"; }
Output:
One rock is bedrock
One rock is slate
One rock is lava
default variable: $_
foreach (qw/bedrock slate lava/)
{print "One rock is $_\n"; }
Output:
One rock is bedrock
One rock is slate
One rock is lava
7. reverse: reverse the item of array
@rocks=qw(bedrock slate rubble lava)
@rocks=reverse(@rocks) --> @rock=lava rubble slate bedrock
8. sort: order the item of array
@rocks=qw(bedrock slate rubble lava)
@rocks=sort(@rocks) --> @rock=bedrock lava rubble slate
9. each: get the index and value of next item of array
@rocks=qw(bedrock slate rubble lava)
while (my($index,$value) = each(@rocks))
{print "$index:$value"; }
output:
0:bedrock
1:slate
2:rubble
3:lava
<STDIN> used for varaible, end with "enter"
<STDIN> used for array, end with "Ctrl+D" (linux) "Ctrl+Z" (windows)
Sub Program (Function)
sub <name> {
....
}
Example:
sub out {
$n=$n+1;
print "Hello World, $n";
}
out --> Hello World, 1
out --> Hello World, 2
out --> Hello World, 3
out --> Hello World, 4
If the name is same as system internal function, you may use &<funcation name> to trigger your own one.
In order to avoid to trigger system internal function, add & to trigger function.
sub out {$n=1; $m=2; $n+$m} --> the sub program will return $n+$m
sub out {$n=1; $m=2; $n+$m; print "hello" ;} --> the sub program will remove the value of $n+$m
return: can use to reture value for specific condition and stop sub function
sub program parameter: transfer as array @_
the first parameter: $_[0]
the second parameter: $_[1]
sub program private variable
A. local: level below this sub program can use
B. my: only this level sub program can use
Example
foreach my $rock(qw/bedrock slate lava/)
{
print "$rock";
}
my $n; --> create private parameter $n
my $n, $m; --> create private parameter $n, public parameter $m
my ($n, $m); --> create private parameter $n, $m
sub max
{
my ($n, $m) =@_;
if ($n > $m) {$n} else {$m}
}
Recommendation: use my to define variable to avoid the impact the program
C. state: keep the value inside the sub program
sub sum
{
state $sum=0;
state @number;
foreach my $number(@_)
{push(@number, $number); $sum+=$number;}
print "The sum of (@number) is $sum";
}
&sum(5,6) --> 11
&sum(1..3)--> 17
&sum(4) --> 21
Use strict
1. create variable: must use my or local start
2. if miss spelling the variable, perl will inform you
3. if variable never be used, perl will inform you
Standard input
<STDIN>
while(defined($line=<STDIN>))
{
print "I saw $line";
}
Trigger perl from command windows: $./my_program file.txt
file.txt will be transfer to internal parameter @ARGV
Use @ARGV by <>
while (<>)
{
chomp;
print "I saw $_";
}
Standard Output
A. print
@array=qw(ab cd ef)
print @array; --> abcdef
print "@array"; --> ab cd ef
B. say: print add \n
say $a; = print "$a\n";
C. printf
%d: number
%s: string
%g: float
$user="Tom";
$day=7;
printf "Hello %s see you in %d days", $user, $day; --> Hello Tom see you in 7 days
printf "%12.3f", 6*7+2/3 --> ......42.667
my @items=qw(Wilma dino pebbles);
my $format="The items are :\n". ("%10s\n" x@items);
printf $format, @items;
Result:
The items are:
Willma
dino
pebbles
File Handle
Internal file handle: STDIN, STDOUT, STDERR, DATA, ARGV, ARGVOUT
Define file handle: use Upper letter or variable
open <file handle>, 'file1';
open <file handle>, '<' , 'file1'; --> only read from file1
open <file handle>, '>' , 'file1'; --> only write into file1
open <file handle>, '>>' , 'file1'; --> if file1 not exist, create it and only write into file1
close <file handle>;
If perl has not privielege to operate on file, perl will feedback undef.
if ( ! open LOG, '>>', 'logfile')
{die "Can not create logfile:$!"; }
die: will stop the program immediate and save error information into $!
use autodie; --> define when program need always operate on files
read file through file handle
while (<LOG>)
{print LOG "hello"; }
Change output: select LOG;
Change output back to standard: select STDOUT;
use variable to define file handle
open my $rock, '>>', 'file1' or die $!;
foreach (qw/slate lava granite/)
{say $rock $_;}
print $rock "hello";
Hash variable
hash index: key
hash value: value
key: string
visit all hash: %
create hash: my %hash
visit one item of hash: $hash{<key>}
my %hash=('foo',35,'bar',12.4,'hello','world',2.5,'hi');
my %hash=(foo => 35,bar => 12.4,hello => 'world',2.5 => 'hi')
get key: my @k=keys%hash;
get value: my @v=values%hash;
if (%hash) --> check whether hash contains one pair of key-value. If yes reture true.
each function: return key-value
while (($key, $value)=each %hash)
{
print "$key=>$value\n";
}
exist function: check key exist or not
if (exists $hash{foo})
{
print "found";
}
delete function: delete key-value
delete $hash(foo);
only can print single hash item, can not put whole hash in it.
internal environment hash table: %ENV
print "PATH is $ENV(PATH)\n";
Control Statement
A. unless: opposite to if
if ($m==1)
{...1...}
else
{...2...}
unless ($m==1)
{...2...}
else
{...1...}
B. until: opposite to while
while ($j < = $i)
{...1...}
until ($j>$i)
{...1...}
C. elsif
if ($n==1) {}
elsif ($n==2) {}
elsif ($n==3) {}
elsif ($n==4) {}
else {}
D. for
for ($i=0; $i<10; $i++)
{...1...}
String Operation
A. index: find substring in string and reply the first position
my $big="Helloworld";
my $small="o";
my $where=index($big, $small); --> 4
my $where1=index($big, $small, $where+1); -->6
B. rindex: find substring in string and reply the last postion
my $big="Helloworldworld";
my $small="wor";
my $where=rindex($big, $small); --> 10
my $where1=rindex($big, $small, $where-1); -->5
C. substr: get substring from string; replace the substring with others
my $word=substr("helloworld",1,5); --> ellow
my $word=substr("helloworld",-3,2); --> rl
my $word=substr("helloworld",1,50); --> elloworld
my $word=stubstr("helloworld",1); --> elloworld
my $word=substr("Hello world",0,5,"Goodbye"); -->Goodbye world
D. sprintf: format output
my $data=sprintf "%4d%02d%02d %2d:%02d%02d" , $yr,$mo,$da,$h,$m,$s; --> 2039/01/19 3:05:08
my $data=sprintf "%4d%2d%2d %2d:%2d%2d" , $yr,$mo,$da,$h,$m,$s; --> 2039/1/19 3:5:8
E. hex / oct: convert 16th / 8th to 10th
hex('DEADBEEF') --> 37535928559
hex: oct('0xDEADBEEF') --> 37535928559
octal: oct('0377') --> 255
binary: oct('0b1101') --> 13
Advanced Technical
A. Order
default sort: order the list by ascii
i. order by number
my $result=sort {$a<=>$b} @some_numbers;
ii. order by letter
my $result=sort {"\L$a" cmp "\L$b"} @some_numbers;
iii. hash order
Comments
Post a Comment