SCALAR DATA =============================================================================== 0377 # 377 octal -0xff # negative FF hex single-quoted strings are a sequence of characters -------------------------------------------------- 'hello' # five characters: h, e, l, l, o 'don/'t' '' # null 'hello # hello, newline, there there' Character Representations -------------------------- \n # newline \r # Return \t # tab \f # formfeed \b # backspace \a # bell \e # escape \007 # octal ASCII value (007=bell) \x7f # hex ASCII value (delete) \cC # Any "control" Character (Control-c) \\ # backslash \" # double quote \l # lowercase next letter \L # lowercase all following letters untill \E \u # uppercase next letter \U # uppercase all until \E \Q # backslash-quote all nonalphanumerics until \E \E # terminates \L, \U, \Q "hello" . "world" # same as "helloworld" "X" . (4 * 5) # "X20" +-----------------------+---------+--------+ | comparison | numeric | string | +-----------------------+---------+--------+ | equal | == | eq | | Not equal | != | ne | | less than | < | lt | | greater than | > | gt | | less than or equal to | <= | le | | greater than or equal | >= | ge | +-----------------------+---------+--------+ string repetition operator -------------------------- "cow" x 3 # is "cowcowcow" "cow" x (2 + 1) # same (3+2) x 4 # "5555" chop and chomp ------------------ $a = "hello"; chop($a); # $a = "hell" $b = "hello\n"; chomp($a); # $a = "hello" chomp($a); # no change more string stuff ------------------- $bigcow = "\Ucow"; # $bigcow = "Cow" $cow = "cow"; $bigcow = "\U$cow"; # same ARRAYS =============================================================================== ($a,17) # two values: the current value of $a and 17 ($a+$b,$c+$d) # two values () # empty list (1 .. 5) # same as (1,2,3,4,5) (1.2 .. 5.2) # same as (1.2,2.2,3.2,4.2,5.2) (2 .. 6,10,12) # (2,3,4,5,6,10,12) ($a .. $b) # range determined by values (1.3 .. 6.1) # (1.3,2.3,3.3,4.3,5.3) @a = qw(cow chicken horse rooster); @cow = qw(one two); @chicken = (4,5,@cow,6,7); #chicken is (4,5,one,two,6,7) @chicken = (8,@chicken); #puts 8 at element 0 ($b,$a) = ($a,$b); # swap values ($d,@cow) = ($a,$b,$c); # give $a to $d, and ($b,$c) to @cow ($e,@cow) = @cow; # remove first element of @cow and give it to $e $a = @cow; # $a gets length of @cow ($a) = @cow; # $a gets first element of cow & discards the rest @a = (7,8,9); @b = reverse(@a); # @b is (9,8,7) @b = reverse(7,8,9); #same thing @x = sort("small", "medium","large"); # x gets "large,"medium","small" @y = (1,2,4,8,16,32,64); @y = sort(@y); # y gets 1,16,2,32,4,64,8 chomp(@stuff); # remove all trailing \n from each value @a = ; # read standard input in a # list context (CTRL-D ends input) CONTROL STRUCTURES =============================================================================== 0 # false, converts to "0" 1-1 # false 1 # converts to "1", so true "" # empty string, false "1" # not "" or "0", so true "00" # not "" or "0", so true "0.000" # true undef # false foreach $i (@somelist) { statement; statement; } example: @a = (1,2,3,4,5); foreach $b (@a) { # prints 12345 print $b; # you could use # just print; here, # and use the $_ variable. } HASHES =============================================================================== Elements are stored in a random order, so don't even try to guess where something is Each key must be unique -------------------- $cow{"aaa"} = "bbb"; # creates key "aaa", value "bbb" $cow{234} = 345; # create key 234, value 345 print $cow{"aaa"}; # prints "bbb" $cow{234} += 3; # makes it 348 @cow_list = %cow; # @cow_list gets ("aaa","bbb",234,345) %chicken = @cow_list; # %chicken is like %cow %smooth = ("aaa","bbb","234",345); # %smooth is like %cow and %chicken %backwards = reverse %normal; # swaps keys with values # best performed on hashes # with unique keys and values # because indentical values will # end up as a single element $cow{"aaa"} = "bbb"; $cow{234} = 345; @list = keys(%cow); # @list gets ("aaa",234) or (234,"aaa") foreach $key (keys(%cow)) { print "at $key we have $cow{$key}\n"; } if (keys(%somehash)) { # if keys() not zero ...; # array is non empty } while (keys(%somehash) < 10) { ...; # keep looping while we have # fewer than 10 elements } if (%somehash) { # if true, then something's in it # do something } %lastname = (); #force %lastname empty $lastname{"cow"} = "barnyard"; $lastname{"chicken"} = "farm"; @lastnames = values(%lastname); # grab the values, @lastname is # ("barnyard","farm") or vice versa while (($first,$last) = each(%lastname)) { print "The last name of $first is $last\n"; } %cow = ("aaa","bbb",234,345); # give %cow two elements delete $cow{"aaa"}; # %cow is now just one key-value pair $score{"cow"} = 23; $score{"chicken"} = 12; $score{"dino"} = 3; # this is redundant @score{"cow","chicken","dino"} = (23,12,3); # a hash slice is simpler @players = qw(cow chicken dino); print "scores are: @score{@players}\n"; BASIC I/O =============================================================================== $a = ; # read the next line @a = ; # each line, separated by each \n or # whatever $/ is set to # the <> operator gets its data from the file or # files specified on the command line #!/usr/bin/perl #kitty, works just like cat while (<>) { # invoke kitty with "kitty file1 file2 file2" print $_; } #command line arguments are stored in the @ARGV perl array @ARGV = ("aaa","bbb","ccc"); while (<>) { # process files aaa, bbb, and ccc print "this line is: $_"; } REGULAR EXPRESSIONS while (<>) { if (/abc/) { # works like grep abc somefile >results # (puts lines in results file) print $_; } } while (<>) { if (/ab*c/) { # works like grep "ab*c" somefile print $_; } } /[abcde]/ # matches a string containing any one # of the first 5 letters of the lowercase alphabet # if you want to put a right bracket in the list, put a \ in front of it [0123456789] # matches any single digit [0-9] # same thing [0-9\-] # matches 0-9 or minus [a-z0-9] # match any single lowercase letter or digit [a-zA-Z0-9_] # match any single letter, digit, or underscore [^0-9] # match any single nondigit [^aeiouAEIOU] # match any single, non-vowel [^\^] # match any single character except an up-arrow +-----------------+------------------+-------------------+-------------------+ | Construct | Equivalent Class | Negated Construct | Equiv. Neg. Class | +-----------------+------------------+-------------------+-------------------+ | (a digit) | [0-9] | \D (digits, not!) | [^0-9] | | \w (word char) | [a-zA-Z0-9_] | \W (words, not!) | [^a-zA-Z0-9_] | | \s (space char) | [ \r\t\n\f] | \S (Space, not!) | [^\r\t\n\f] | +-----------------+------------------+-------------------+-------------------+ [\da-fA-F] # match one hex digit $_ = "cow xxxxxxxxx chicken"; s/x+/boom/; # cow boom chicken $_= "foot fool buffoon"; s/foo/bar/g; # $_ = "bart barl bufbarn" $_ = "hello, world"; $new = "goodbye"; s/hello/$new/; # $_ = "goodbye, world"; $_ = "this is a test"; s/(\w+)/<$1>/g; # " " # $1 is set to the data within the # first parenthesized pattern match $which = "this is a test"; $which =~ s/test/quiz; # $which is "this is a quiz" $line = "merlin::118:10:Randal:/home/merlin:/usr/bin/perl"; @fields = split(/:/,$line); # @fields is ("merlin","","118"......) @words = split; # same as @words = split(/\s+/, $_); #to rebuild the passord line $outline = join(":",@fields); $result = (join "+", "", @fields); # puts a + in front of each element $output = join ("\n", @data, ""); # puts a \n after each element FUNCTIONS =============================================================================== sub sum_of_a_and_b { return $a + $b; } $a = 3; $b = 4; $c = sum_of_a_and_b(); # c gets 7 sub list_a_and_b { return($a,$b); } @c = list_a_and_b(); # gets ($a,$b) sub say { print "$_[0], $_[1]!\n"; } say("hello","world"); say("goodbye","cruel world"); sub add { $sum = 0; foreach $_ (@_) { $sum += $_; } return $sum } print add(1 .. 5); # print 15 sub hello { my($n,@values); ($n,@values) = @_; # split up the array of arguments } @new = hello(100,@list); the local function: ------------------- $value = "original"; tellme(); spoof(); tellme(); sub spoof { local ($value) = "temp"; tellme(); } sub tellme { print "current value is $value\n"; } this prints out: current value is original current value is temp current value si origianl OTHER CONTROL STRUCTURES =============================================================================== while (something) { thing; thing; if (somecondition) { other; other; last; # break out of the while loop } morestuff; } while (something) { thing; thing; if (somecondition) { other; other; next; # morestuff is skipped and the next # iteration of the loop is done } morestuff; } while (something) { thing; thing; if (somecondition) { other; other; redo; # jump to the beginning without # evaluating the control expression } morestuff; } OUTER: for (something) { for (something) { if (somecondition) { statement; last OUTER; # refers to the outer for # structure (breaks out of # the whole thing) } if (somecondition) { next OUTER; # refers to the # outer for structure } } } FILEHANDLES AND FILE TESTS =============================================================================== open(FILE, "somefile") # open for read open(FILE, ">somefile") # open for write open(FILE, ">>somefile") # open for append close(FILE, "somefile") # close the file open(FILE, "somefile") || die "couldn't read somefile: $!"; #output something to a file print LOGFILE "this is done\n"; #copy data from one file to another open(IN,"$a") || die "cannot open $a for reading: $!"; open(OUT,">$b") || die "cannot create $b: $!"; while () { print OUT $_; } close(IN) || die "can't close $a: $!"; close(OUT) || die "can't close $b : $!"; # file test -e tests if a file or directory exists if (-e "index.html") { print "found it\n"; }else{ print "can't find it\n"; } DATA TRANSFORMATIONS =============================================================================== #finding a substring #$x = index($string,$substring); $where = index("hello","e"); # $where gets 1 $where = index("a very long string","long");# $where gets 7 $where = index("a very long string","lame");# $where gets -1 #$x = index($bigstring,$littlestring,$skip); $where = index("hello world","o",5); # $where gets 7 (second o) #scan from right to left $w = rindex("hello world","l"); # $w gets 9 (rightmost l) $w = rindex("hello world","o",6); # $w gets 4 (first before 6) # extract and replace a substring # $s = substr($string,$start,$length); $hello = "hello world!"; $grab = substr($hello,3,2); # $grab gets "lo" $grab = substr($hello,7,100); # $grab gets "orld!" $stuff = substr("a very long string",-3,3); # last three chars $stuff = substr("a very long string",-3,1); # "i" $hw = "hello world!"; substr($hw,0,5) = "howdy"; # $hw is now "howdy world!" transliteration ------------------ tr/ab/ba/; # change a's into b's, vice versa $_ = "cow and chicken"; tr/fc/cf/; # "fow and fhifken" tr/abcde/ABCDE/; # "Cow AnD ChiCkEn" tr/a-z/A-Z/; # "FOW AND FHIFKEN" # if the new string is shorter than the old string, # the last character of the new string is # repeated enough times to make the strings equal length. tr/A-Z/x/; # "xxx xxx xxxxxxx" # d means delete all character that aren't in the new string $_ = "cow and chicken"; tr/a-z/ABCDE/d; # "C AD CCE" $_ = "cow and chicken"; $count = tr/a-z//; # $_ is unchanged, but $count is 13 $count = tr/a-z/A-Z/; # $_ is uppercased, and $count is 13 # a cool way to count occurances of a string while (/pattern/g) { $count++; } # c is the opposite of d $count = tr/a-z//c; # $_ unchanged, but $count is 2 (the two spaces) tr/a-z/_/c; # "cow_and_chicken" (non-letters are changed) tr/a-z//cd; # "cowandchicken" (deletes non-letters) # s squeezes multiple consecutive copies of the resulting # translated letter into one copy. $_ = "aaabbbcccdefghi"; tr/defghi/abcddd/s; # "aaabbbcccabcd" $_ = "cow and chicken, horse and rooster"; tr/a-z/X/s; #"X X X, X X X" $_ = "cow and chicken, horse and rooster"; tr/a-z/_/cs; # "cow_and_chicken_horse_and_rooster" $names = "cow and chicken"; $names =~ tr/aeiou/X/; # cXw Xnd chXckXn CGI =============================================================================== use CGI qw(:cgi); # use these two lines when using the CGI Perl module $cgi = new CGI; $user = $cgi->param('user'); # CGI variable declaration