perl basic
"Notes from my early perl days. Life was simple back then. No readability, no named variables, no problem.
Variables
Variables are Case-Sensitive
$ScalarVar=...
@Array=(...);
%Hash={...}
- To separate Variables from a scalar value
- ${Var1}Go instead of $Var1Go.
Literals
' ': single quote- anything, incl. NL var not expanded, no formatting code
ex:
'hello there' # same as ""hello\nthere""
- "" ""
- double quote- var expanded
FORMATTING CODE:
\l= lowercase next letter
\L..\E= lowercase (""\LJOE""=""joe"")
\u=uppercase next letter
\U..\E=uppercase (""\Ufred"" = ""FRED"")
ex: ""\u\LDAVE"" = ""Dave""
\cX = ctrl-X, X can be any char
\007 = octal, \0x7f=hex code
\Q ..\E=backslash quote
\$= ""$"" ie dollar sign
numeric operator:
<,<=,==,>,>=,!=,++,--,*=,+= **=power()
STRING
- Index(str,substr, [startPosition]);
- Finds 1st occurrence of substr in str and returns Position.
- Returns -1 if not found.
- StartPosition: search starts at startPosition, not 0.
- $result=Index('abcd','c'); # $result = 2;
- rindex(str,substr, [startPosition]);
- Finds 1st occurrence from backward order (rightmost).
- StartPosition starts from that position and goes backward.
- $I=Substr(str,start,length);
- Returns substring based on position and length.
- $a=substr(""abcd"",2,2) ; # $a=""cd"";
- If $start is minus, it starts from end of string.
- $a=substr(""abcde"",-2,2); # $a='de';
- substr($strVar,start,length)=""new string"";
- To replace part of string
ex:
$a=""hello world""; substr($a,0,5)=""abcde""; #$a='abcde world'; substr($a,0,5)='hi; # $a='hi world'; Automatically resizes. Substr($a,-6,5)='pppppppp'; # replaces 'world' and longer # ie 'hello pp
- $str=sprintf("".."",$var);
- printf in a var
- chomp($name);
- removes only the NL if it exists
- chomp(@texts); # removes NL from all array elem.
- chomp($a=<STDIN>);
- shortcut for $a=<STDIN>;chomp($a);
- chop($name);
- removes any last char
- undef
- undefined type, when var is not assigned
string operator
- ""hello"" . ""world""
- concat
- eq,ne,lt,gt,le,ge
- comparison
- ""fred"" x 3
string repetition, ""fredfredfred""
""5"" x 3 # ""555""
- $str++
Magic increment. Increments a string containing number.
- ""000099"" -> ""000100"".
- There is NO magical decrement.
ARRAY
Assignment of entire array
ex:
@words=(""camel"",""bat"",""apple""); @words=qw(camel bat apple); #separated by whitespace @a=(1,2,3,""fred"",""dave""); @a=(); #Empty array @a=(1..4); # =(1,2,3,4) @a=(1.2..4.2); # =(1,2,3,4) @a=(2..4,7); #(2,3,4,7) @a=($a..$b); #(whatever $a and $b ranges) @a=1; #assigns array ie @a=(1); @a=@b; #copy print ""@a""; #prints all elements of array @a
Multiple Assignment:
($a,$b)=($b,$a); #swap a,b ($a,$b,$c)=(1,2,3); #a=1,b=2,c=3 ($a,@b)=($c,$d,$e); $a=$c;@b=($d,$e)
SCALAR OF ARRAY:
$i=@a; # i=size of array a ($i)=@a; # i=1st element of array a $#a= index value of last element of @a @a=qw(a b c); $#a contains 2 $a[0]=5; #set element. 1st element is now set to 5
SLICE:
@a[0,1]=@[1,0]; #swap 0,1st element
@a[1,2] =('a','b');# a[1]='a',a[2]='b'
@a[0,1,2] # same as @a[0..2]
@b=(3,4,5);@a[@b]... #=@a[3,4,5]
- OUT OF RANGE
- out of range of array => returns undef
- push(@a,$newValue);
same as @a=(@a,$newValue);
ex:
push(@a,@b); push(a,4,5,7); #push multiple items
- $oldValue = pop(@a);
- removes last element
- $x=shift(@a);
- ($x,@a)=@a; # ie 1st elem->$x, @a gets rest, ie Queue
- $x=shift; # $x=shift @_; for param
unshift(@a,7); # same as @a=(7,@a);
- @a=reverse (@a);
- reverse array order
- reverse(7,8,9); #-> (9,8,7)
@a=sort('b','c','a'); # ('a','b','c'), only alphabetical sort, not numerical
@a=<stdin>; #each line is stored in an element of @a. CTRL-D to end.
%password=qx(fred a1 jack b2 tom c3); #???
HASHES
# Hash value must be Scalar, not array/list. TO have arrays, use reference.
$I{""John""}=7; # creates key ""John"", and value 7
@a=%I; # @a gets all keys and value so hash %I
%b=@a;
%c=(""key1"",""val1"",""key2"",""val2"",...);
%a=%b; # copy
- %a=reverse %b;
keys and values are reversed! But if there are any values that are identical, it will only store 1 set, not both.
('a',1,'b',2,'c',1) =>reverse=> (1,c,2,b,1,a)->(1,c,2,b)?
- @a=keys(%I);
- # returns @ of all keys
foreach $I (keys (%a)) { print ""$a{$I}n""}
- $n= %a;
- # returns 0/1 true/false if hash is defined or not
- @a=values(%hash);
- # lists of values
- @a=each(%has);
- # iterates, returns pair of key,value elem until end. # returns empty list () when finished. While ($first,$last)=each($name) {...}
- delete $hash{""key""};
- # removes element from hash
SLICE:
($a{a},$a{b},$a{c})=(1,2,3);
# same as $a{a}=1, $a{b}='b',...
@a{'a','b','c'}=(1,2,3);
print ""@a{'a','b','c'}; # output=1 2 3
- Merging
@league{keys %score}=values %score;
slower merge: %league=(%league,%score);
FUNCTIONS
print()
print(""..""); print ""..."";
- sub f { }
- #all vars are global even w/in sub except private var
- f ();
- # call function f
- return $a;
# func can return value
$i=someFunctionThatReturnsValue();
- @_
# contains list of args, 1st arg=$_[0], 2nd arg=$_[1],...
my($arg1,$arg2)= @_; #faster
- my($var1,$var2,..);
# declare var to be private, visible only within current scope
my $var1= ""hello"";
- local($var1,$var2,...);
# declare var to be semi-private. Original var is restored when func returns
$a=""original""; f(); #$a is restored to ""original"" after returning from func f() sub f { local ($a); $a=7; } sub f { local $_; } # used frequently.- use strict;
- #forces all var to be declared (either via my() or local())
- our($var1,$var2,...);
- # declare global variable from within a package
- *var; ('star-var')
- # TypeGlobbing
CONTROL STRUCTURE
- If (...) {...}
- # if it is a 1-line code, statement doesn't need "";"" semi-colon.
If () {} elsif () {} else {}
- $a=<TestExpr> ? <TrueExpr> : <FalseExpr>;
- same as in C
- Unless() { }
- # same as if(!...) { }
While() { }
Until () { }
Do { } while ();
Do { } until ();
- {exp2} if (exp1);
# backward if's: if (exp1) exp2;
a++ if (b<0);
- {exp2} unless (exp1);
- #backward unless : unless (exp1) exp2;
- {exp2} while (exp1);
- #backward while: while(exp1) {exp2}
- {exp2} until (exp1);
- #backward until: until(exp1) {exp2}
- exp1 || exp2;
# Do exp1. If exp1 is false, do exp2.
DoThis || die(""failed"");
- Exp1 && exp2;
- # do exp1. If exp1 is true, do exp2.
For-Loop
- for ( ; ; ) { }
- #same as C
- foreach $I (@a) { } #$I is restored when loop exits.
$I is Alias/Reference, not just a copy. So assigning $I will alter @a
- By default, $_ is assigned if $I is not present.
Foreach(@a) { print} # prints $_
Foreach(@a) {$_=7} # @a=(7,7,7,..)
- Last;
# breaks out of loop
last LABEL; # breaks out of loop w/ label LABEL.
- next;
# goes to end of loop and continue
next LABEL; # does next on loop labeled LABEL
- redo;
#goes to beginning of loop and continue
redo LABEL; # does redo on loop labeled LABEL
REFERENCE
- $aref=\$a;
# \ indicates reference. $aref contains ref to $a
$aref=\@a; $aref=\%a;
- $aref=[lists...]
# [] returns anonymous list and returns ref
$ar=[1 2 3]; #same as $a=(1,2,3);$ar=$a;
- $aref={....}
- # { } returns anonymous hash and returns ref
@{$aref}
@$aref
# dereference aref
# {} are optional: @$aref
$aref=\@array;
print @{$aref}; # print content of array
print ${$aref}[3]; # print 4th element of array
${$aref}[7]=34; #assign array
- $aref->[n]
- # shortcut to ${$aref}[n]
%{$href}
%$href
# dereference
# {} are optional.
$href=\%hash;
print %{$href}; # print hash
print ${$href}{""b""}; #print $hash{'b'}
${$href}{'app'}=34;
- $href->{'ban'}
- #shortcut to ${$href}{'ban'}
ex (PerlRefTut):
@a=([1,2,3],[4,5,6],[7,8,9]); # @a is an array of 3 elem containing ref to arrays # ie $a[0] -> ref to [1,2,3] $a[0]->[2]=='3' #3rd elem of 1st array is '3'.
- $aref[n][m]
- shortcut to $aref[n]->[m]
- ie same ex above, $a[0][2]= $a[0]->[2] =='3'
- ref($var)
- Returns False if $ var is not reference.
- returns SCALAR, HASH, or ARRAY if it is a reference to those.
