8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
1/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
2/20
$mixed[2] = 37; # @mixed is ("three",3.13,37) - grows automatically@joined = (@mixed,8); # @joined is ("three",3.13,37,8)@sl = @nums[0,-1,1]; # @sl is (1,3,2) - array slice (specific indices)@sl = @nums[0..2]; # @sl is (1,2,3) - array slice (span)$len = scalar(@nums); # an array in scalar context is the list length (3)$last_index = $#nums; # $last_index is 2 (the last index in the list)
$#nums = -1; # @nums is () - empty
### hashes (maps of keys and values)%ages = ("jim"=>18,"ted"=>21); # the key "jim" has a value of 18%same = ("jim",18,"ted",21); # => is exactly like ,%mix_hash = (1=>"bla","hi"=>22.1); # any scalar can be a key or value%empty_hash = (); # empty hash counts as FALSE, full is TRUE
# hash operations$jims_age = $ages{"jim"}; # $jims_age is 18$ages{"jim"}++; # key "jim" has value of 19 in %ages
$ages{"ron"} = 24; # key "ron" with value 24 added to %ages@sl = @ages{"ted","ron"}; # @sl is (21,24) - hash slice$stats = scalar(%ages); # string eg. "1/16" - 1 used bucket out of 16 alloced
### references (scalar that holds a pointer to another type)$scalarref = \$num;$arrayref = \@mixed;$hashref = \%ages;
# reference operations$num_copy = $$scalarref; # dereference using {type}$reference@mixed_copy = @$arrayref;$value = $$hashref{"jim"};$value = $arrayref->[0]; # or dereference using $reference->$value = $hashref->{"jim"};
Conditionals
############################################################################### name: main# purpose: show the basic conditionals
##############################################################################
# regular c style if statement, must use blocksif (defined($value) && ($value == 1)) # defined() tests for undef{
print "value equals 1\n";}
# if-else, must use blocksif (($job eq "millionaire") || ($state ne "dead")) # eq,ne are used for strings{
print "a suitable husband found\n";}else
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
3/20
{print "not suitable\n";
}
# unless is the opposite of if, must use blocksunless (($age >= 18) and ($age < 80)) # and,or,not are also ok
{abramprint "too old\n";
}
# short forms (no blocks needed if a single statement comes before)print "ok" if $ok;print "ok" unless not $ok;
# and the true perl wayopen(FILE) or die "cant open file";
Loops and Iterations
############################################################################### name: main# purpose: show the flow blocks##############################################################################
# for (regular c style), must use a blockfor ($i=0; $i
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
4/20
while ($i < 10) # enter block if condition is TRUE{
print "iteration number $i\n";$i++;
}until ($i == 0) # enter block if condition is FALSE
{$i--;print "back to $i\n";
}
# do while / until just like in c, must use blocks$i = 0;do{
print "this will print\n"; # enter block once before evaluating} while ($i != 0);
do{
print "this too\n";} until ($i == 0);
# short forms (no blocks needed if a single statement comes before)print "a" for (1..10);read_next_line() while not end_of_file();read_next_line() until end_of_file();
# next and last statements are similar to c continue and breakfor ($i=0; $i
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
5/20
sub seventeen1 # return keyword indicated return value{
return 17;}sub seventeen2 # if no return exists, retval is the last expression{
17;}$num = seventeen1() + seventeen2() + 53;sub retlist # all datatypes can be returned{
return (1,2,3);}($one,$two,$thr) = retlist; # () are optional (even when we have args)
# arguments
abram
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
6/20
sub has_args{
@func_arguments = @_; # all arguments are members of the list @_$first_arg = $_[0]; # returns undef if no arg given($arg1,$arg2,$arg3) = @_; # the common perl way to handle function arguments
}
has_args($num,@l1,22,@l2); # all arguments are flattened into one listsub takes_two_lists # to pass several lists / hashes, use references{
($l1ref,$l2ref) = @_;@list1 = @$l1ref;
}takes_two_lists(\@a,\@b);
# prototypes (limited compile-time argument checking)sub two_scalars($$) { }; # two_scalars(12,"hello");sub scalar_n_list($@) { }; # scalar_n_list("scalar",1,2,3);
sub array_ref(\@) { }; # array_ref(@array);
Regular Expressions
############################################################################### name: main# purpose: show regular expression usage##############################################################################
# matching$call911 = 'Someone, call 911.'; # the string we want to match upon$found = ($call911 =~ /call/); # $found is TRUE, matched 'call'@res = ($call911 =~ /Some(...)/); # @res is ('one'), matched 'Someone'$entire_res = $&; # $entire_res is 'Someone'$brack1_res = $1; # $brack1_res is 'one', $+ for last brackets($entire_pos,$brack1_pos) = @-; # $entire_pos is 0, $brack1_pos is 4($entire_end,$brack1_end) = @+; # $entire_end is 7, $brack1_end is 7# global matching (get all found)$call911 =~ /(.o.)/g; # g is global-match, $1 is 'Som', $2 is 'eon'@res = ($call911 =~ /(.o.)/g); # @res is ('Som','eon'), $& is 'eon'
# substituting$greeting = "hello world"; # the string we want to replace in$greeting =~ s/hello/goodbye/; # $greeting is 'goodbye world'
# splitting@l = split(/\W+/,$call911); # @l is ('Someone','call','911')@l = split(/(\W+)/,$call911); # @l is ('Someone',', ','call',' ','911','.')
# pattern syntax$call911 =~ /c.ll/; # . is anything but \n, $& is 'call'$call911 =~ /c.ll/s; # s is singe-line, . will include \n, $& is 'call'
$call911 =~ /911\./; # \ escapes metachars {}[]()^$.|*+?\, $& is '911.'$call911 =~ /o../; # matches earliest, $& is 'ome'$call911 =~ /g?one/; # ? is 0 or 1 times, $& is 'one'
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
7/20
$call911 =~ /cal+/; # + is 1 or more times, $& is 'call', * for 0 or more$call911 =~ /cal{2}/; # {2} is exactly 2 times, $& is 'call'$call911 =~ /cal{0,3}/; # {0,3} is 0 to 3 times, $& is 'call', {2,} for >= 2$call911 =~ /S.*o/; # matches are greedy, $& is 'Someo'$call911 =~ /S.*?o/; # ? makes match non-greedy, $& is 'So'$call911 =~ /^.o/; # ^ must match beginning of line, $& is 'So'
$call911 =~ /....$/; # $ must match end of line, $& is '911.'$call911 =~ /9[012-9a-z]/;# one of the letters in [...], $& is '91'$call911 =~ /.o[^m]/; # none of the letters in [^...], $& is 'eon'$call911 =~ /\d*/; # \d is digit, $& is '911'$call911 =~ /S\w*/; # \w is word [a-zA-Z0-9_], $& is 'Someone'$call911 =~ /..e\b/; # \b is word boundry, $& is 'one', \B for non-boundry$call911 =~ / \D.../; # \D is non-digit, $& is ' call', \W for non-word$call911 =~ /\s.*\s/; # \s is whitespace char [\t\n ], $& is ' call '$call911 =~ /\x39\x31+/; # \x is hex byte, $& is '911'$call911 =~ /Some(.*),/; # (...) extracts, $1 is 'one', $& is 'Someone,'$call911 =~ /e(one|two)/; # | means or, $& is 'eone'
$call911 =~ /e(?:one|tw)/;# (?:...) does not extract, $& is 'eone', $1 is undef$call911 =~ /(.)..\1/; # \1 is memory of first brackets, $& is 'omeo'$call911 =~ /some/i; # i is case-insensitive, $& is 'Some'$call911 =~ /^Some/m; # m is multi-line, ^ will match start of entire text$call911 =~ m!call!; # use ! instead of /, no need for \/, $& is 'call'
Special Variables
############################################################################### name: main# purpose: show some special internal variables##############################################################################
# $_ - default input print for (1..10); # in many places, no var will cause work on $_print $_ for $_ (1..10); # same as above
# $. - current line in last file handleabramwhile (!( =~ /error/i)) {};print "first error on line $.\n";
# $/ - input record separator (default is "\n")undef $/;
$entire = ; # read entire file all at once$/ = "512";$chunk = ; # read a chunk of 512 bytes
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
8/20
# $\ - output record separator (default is undef)$\ = "\n"; # auto \n after print
print 'no need for LF';
# $! - errno / a string description of error
open(FILE) or die "error: $!";
# $@ - errors from last evaleval $cmd;
print "eval successful" if not $@;
Standard IO
############################################################################### name: main# purpose: show some basic IO and file handling
##############################################################################
# open a file a la shellopen(IN, "< input.txt") or die "cant open input file: $!";open(OUT, ">> output.txt") or die "cant open output file: $!";# binmode(IN) to change IN from txt mode to binary mode
# read records from a file (according to $/)while ($line = ) # returns next line, or FALSE if none left{
# write data to a fileprint OUT $line;
}
# cleanupclose(IN);close(OUT);
# check if file existsprint "$filename exists" if (-e $filename);
# check the file sizeprint "$filename file size is ".(stat $filename)[7];
# get all the txt files in current directory@txtfiles = ; # perl globbing@txtfiles = `dir /b *.txt`; # or use the shell (slower), needs chomping
Useful Functions and Keywords
############################################################################### name: main
# purpose: show some basic functions and keywords of perl##############################################################################
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
9/20
# scalar / string functionsforeach (`dir /b`) { chomp; print; } # chomp removes \n tail
(abramaccording to $/)$ext = chop($file).$ext for (1..3); # chop removes last char and returns it print 'a is '.chr(ord('a')); # ord converts chr to num, chr is opposite print lc("Hello"), uc(" World"); # prints 'hello WORLD' print length("hello"); # prints '5'$three_a = sprintf("%08x",58); # just like regular c sprintf
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
10/20
print($type) if ($type = ref $ref); # prints 'SCALAR'/'ARRAY'/'HASH'/'REF'
# regexps and pattern matching functions print quotemeta('[.]'); # prints '\[\.\]'@words = split(/W+/,$sentence); # splits a string according to a regexp
# array / list functions@three_two_one = reverse(1,2,3); # returns a list in reverse
print pop(push(@arr,'at end')); # prints 'at end', no change to @arrprint shift(unshift(@arr,'at start'); # prints 'at start', no change to @arr@after = grep(!/^\s*#/, @before); # weed out full comment lines$sentence = join(' ',@words); # turns lists into strings with a delim
print sort ; # sort string lists in alphabetical orderdelete @arr[3..5]; # deletes the 3rd,4th,5th elements in @arr
print "length is ".scalar @arr; # scalar evaluates expressions as scalars
# hash related functionsdelete @hash{"key1","key2"}; # deletes these keys from the hash
print $hash{$_} foreach (keys %hash); # prints all hash values by checking keys print values(%hash); # same but different
# misc functions and keywordssleep(10); # causes the script to sleep for 10 secsexit(0) if $should_quit; # exits the script with a return valueuse warnings; use strict; # imports new external modulesno warnings; no strict; # un-imports imported external modulesmy $var; # declare a local variable (strict)undef($null) if defined($null); # check if a variable is definedeval '$pn = $0;'; print $pn; # interpret new perl code in runtimesystem("del $filename"); # run commands in the shell (blocking)system("start calc.exe"); # run commands in the shell (nonblocking)@files = `dir /b`; # run & get output of shell commands ("")
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
11/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
12/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
13/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
14/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
15/20
abram
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
16/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
17/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
18/20
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
19/20
abram
8/9/2019 Syntax Perl No Blocks Needed if a Single Statement Comes Before Perl Syntax
20/20abram
Top Related