perl practical extraction and report language. perl2 scalar data n number or string of characters n...
Post on 22-Dec-2015
218 views
TRANSCRIPT
PerlPerl
Practical Extraction and Practical Extraction and Report LanguageReport Language
Perl 2
Scalar DataScalar Data Number or string of charactersNumber or string of characters NumbersNumbers
– Internally, all numbers are double-Internally, all numbers are double-precision floating pointprecision floating point
Single-quoted stringsSingle-quoted strings– Any character, with 2 exceptions, is Any character, with 2 exceptions, is
legal between quoteslegal between quotes \' prints as \' prints as '' \\ prints as \\ prints as \\
Perl 3
Scalar DataScalar Data Double-quoted stringsDouble-quoted strings
– Backslash specifies control characters, Backslash specifies control characters, or, through octal and hex notation, any or, through octal and hex notation, any charactercharacter \n - newline\n - newline \r - carriage return\r - carriage return \t - tab\t - tab \b - backspace\b - backspace \a - bell\a - bell \e - escape\e - escape \007 - octal ASCII value\007 - octal ASCII value \x87 - hex ASCII value\x87 - hex ASCII value
Perl 4
Scalar DataScalar Data
Double-quoted stringsDouble-quoted strings \cC - control character (here, control C)\cC - control character (here, control C) \\ - backslash\\ - backslash \" - double quote\" - double quote \l - lowercase next letter\l - lowercase next letter \L - lowercase all following letters until \E\L - lowercase all following letters until \E \u - uppercase next letter\u - uppercase next letter \U - Uppercase all following letters until \E\U - Uppercase all following letters until \E \E - terminates \L or \U\E - terminates \L or \U
Perl 5
Scalar DataScalar Data
Numeric operatorsNumeric operators– Addition (+)Addition (+)– Subtraction (-)Subtraction (-)– Multiplication (*)Multiplication (*)– Division (/)Division (/)– Exponentiation (**)Exponentiation (**)– Modulus (%)Modulus (%)– Comparison operatorsComparison operators
<, <=, ==, >=, >, !=<, <=, ==, >=, >, !=
Perl 6
Scalar DataScalar Data
String operatorsString operators– Concatenation (.)Concatenation (.)– String repetition (x)String repetition (x)
"bill"x4 is "billbillbillbill""bill"x4 is "billbillbillbill" (4+2) x 3 is 6 x 3 or "6" x 3 or "666"(4+2) x 3 is 6 x 3 or "6" x 3 or "666" "a"x3.7 is "aaa""a"x3.7 is "aaa" "a"x0 is """a"x0 is ""
Perl 7
Scalar DataScalar Data
String operatorsString operators– Comparison operatorsComparison operators
lt, le, eq, ge, gt, nelt, le, eq, ge, gt, ne– 7 < 30 is true7 < 30 is true– 7 lt 30 is false7 lt 30 is false
Perl 8
Scalar DataScalar Data
Conversion between strings and Conversion between strings and numbersnumbers– String used as operand for numeric String used as operand for numeric
operatoroperator String converted to its equivalent String converted to its equivalent
numeric valuenumeric value– " 45.67bill" converts to 45.67" 45.67bill" converts to 45.67– "bill" converts to 0"bill" converts to 0
Perl 9
Scalar DataScalar Data
Conversion between strings and Conversion between strings and numbersnumbers– Numeric value used as operand for Numeric value used as operand for
string operatorstring operator Value calculated and converted into Value calculated and converted into
stringstring– "z" . (3 + 5) is "z8""z" . (3 + 5) is "z8"
Perl 10
Scalar DataScalar Data
Scalar variablesScalar variables– Begin with $, followed by letter, Begin with $, followed by letter,
possibly followed by more letters, possibly followed by more letters, digits, or underscoresdigits, or underscores
– Case sensitiveCase sensitive
Perl 11
Scalar DataScalar Data
Variable assignmentVariable assignment– Value of a scalar assignment is the Value of a scalar assignment is the
value of the right-hand sidevalue of the right-hand side– $z = 3 * ($y = 2);$z = 3 * ($y = 2);– $a = $b = 7;$a = $b = 7;
Perl 12
Scalar DataScalar Data
Binary assignment operatorsBinary assignment operators– $a = $a + 8;$a = $a + 8;
$a += 8;$a += 8;– $string = $string . "cat";$string = $string . "cat";
$string .= "cat";$string .= "cat";
Perl 13
Scalar DataScalar Data
Autoincrement and autodecrementAutoincrement and autodecrement– $z = 8;$z = 8;
$y = ++$z; #$z and $y are both 9$y = ++$z; #$z and $y are both 9– $z = 8;$z = 8;
$y = $z++; #$y is 8, but $z is 9$y = $z++; #$y is 8, but $z is 9– $z = 8.5;$z = 8.5;
$y = ++$z; #$z and $y are both 9.5$y = ++$z; #$z and $y are both 9.5
Perl 14
Scalar DataScalar Data chop( )chop( )
– Returns last character of string argumentReturns last character of string argument– Has side effect of removing this last Has side effect of removing this last
charactercharacter InterpolationInterpolation
– $a=7; print "Value is $a";$a=7; print "Value is $a"; Prints Prints Value is 7Value is 7
– $b='Bill'; print "Name is $b";$b='Bill'; print "Name is $b"; Prints Prints Name is BillName is Bill
– $b='Bill'; print "Name is \$b";$b='Bill'; print "Name is \$b"; Prints Prints Name is $bName is $b
Perl 15
Scalar DataScalar Data
<STDIN> as a scalar value<STDIN> as a scalar value– $a = <STDIN>;$a = <STDIN>;
chop($a);chop($a);– chop($a=<STDIN>);chop($a=<STDIN>);
OutputOutput– print("Hi there\n");print("Hi there\n");– print "Hi there\n";print "Hi there\n";
Perl 16
Scalar DataScalar Data
undefundef– Value of undefined variableValue of undefined variable
Looks like zero when used as a numberLooks like zero when used as a number Looks like the empty string when used as Looks like the empty string when used as
a stringa string <STDIN> returns undef when input is <STDIN> returns undef when input is
control-Dcontrol-D
Perl 17
ArraysArrays
LiteralsLiterals– (4,5,6)(4,5,6)– ("Bill",7,8,9)("Bill",7,8,9)– ($a,8)($a,8)– ($z+$h,7,8)($z+$h,7,8)– (1..5,4,7) # (1,2,3,4,5,4,7)(1..5,4,7) # (1,2,3,4,5,4,7)– (1.3..5.3) # (1.3,2.3,3.3,4.3,5.3)(1.3..5.3) # (1.3,2.3,3.3,4.3,5.3)
Perl 18
ArraysArrays
LiteralsLiterals– (2.3..7.1) # (2.3,3.3,4.3,5.3,6.3) (2.3..7.1) # (2.3,3.3,4.3,5.3,6.3) – () # the empty array() # the empty array– print (5, 6, "cat", $a)print (5, 6, "cat", $a)
Perl 19
ArraysArrays
Array variablesArray variables– Begins with @Begins with @
Array assignmentArray assignment– @a=(1,2,3);@a=(1,2,3);
@b=@a;@b=@a;– @z=5; # @z is (5)@z=5; # @z is (5)– @z=("b",6);@z=("b",6);
@w=(4,5,@z,9); # @w is (4,5,"b",6,9)@w=(4,5,@z,9); # @w is (4,5,"b",6,9)
Perl 20
ArraysArrays
Array assignmentArray assignment– ($a,$b,$c)=(4,5,6) # $a=4, $b=5, ($a,$b,$c)=(4,5,6) # $a=4, $b=5,
$c=6$c=6– ($a,$b)=($b,$a) # switches values of ($a,$b)=($b,$a) # switches values of
$a and $b$a and $b– ($z,@w)=($a,$b,$c) # $z is $a, @w is ($z,@w)=($a,$b,$c) # $z is $a, @w is
($b,$c)($b,$c)
Perl 21
ArraysArrays
Array assignmentArray assignment– $a=(4,5,6); # $a is 6, from the $a=(4,5,6); # $a is 6, from the
comma operatorcomma operator
($a)=(4,5,6); # $a is 4($a)=(4,5,6); # $a is 4
@x=(4,5,6);@x=(4,5,6);
$a=@x; # $a is 3, the length of @x$a=@x; # $a is 3, the length of @x
($a)=@x; # $a is 4($a)=@x; # $a is 4
Perl 22
ArraysArrays
Element accessElement access@x=(4,5,6);@x=(4,5,6);$a=$x[0]; # $a is 4$a=$x[0]; # $a is 4$x[0]=9; # @x is (9,5,6)$x[0]=9; # @x is (9,5,6)$x[2]++; # @x is (9,5,7)$x[2]++; # @x is (9,5,7)$x[1] += 5; # @x is (9,10,7)$x[1] += 5; # @x is (9,10,7)
($x[0],$x[1])=($x[1],$x[0]); # @x is ($x[0],$x[1])=($x[1],$x[0]); # @x is (10,9,7)(10,9,7)
Perl 23
ArraysArrays
Element accessElement access@x[0,1]=@x[1,0]; # @x is (9,10,7)@x[0,1]=@x[1,0]; # @x is (9,10,7)
@x[0,1,2]=@x[1,1,1]; # @x is @x[0,1,2]=@x[1,1,1]; # @x is (10,10,10)(10,10,10)$b=$x[8]; # $b is undef$b=$x[8]; # $b is undef$x[4] = "b"; # @x is (10,10,10,undef, $x[4] = "b"; # @x is (10,10,10,undef, "b")"b")$#x=3; # $#x is index value of last $#x=3; # $#x is index value of last element of @x, so @x is element of @x, so @x is (10,10,10,undef)(10,10,10,undef)
Perl 24
ArraysArrays
push( ) and pop( ) operatorspush( ) and pop( ) operatorspush(@x,$a); # @x = (@x,$a)push(@x,$a); # @x = (@x,$a)
push(@x,6,7,8); # @x = (@x,6,7,8)push(@x,6,7,8); # @x = (@x,6,7,8)
$last=pop(@x); # removes last $last=pop(@x); # removes last element of @xelement of @x
shift( ) and unshift( ) operatorsshift( ) and unshift( ) operatorsunshift(@x,6,7,8); # @x = (6,7,8,@x)unshift(@x,6,7,8); # @x = (6,7,8,@x)
$first=shift(@x); # ($first,@x) = @x$first=shift(@x); # ($first,@x) = @x
Perl 25
ArraysArrays
reverse( ) operatorreverse( ) operator@x = (6,7,8);@x = (6,7,8);
@y = reverse(@x); # @y = (8,7,6)@y = reverse(@x); # @y = (8,7,6) sort( ) operatorsort( ) operator
@x = (1,2,4,8,16,32,64);@x = (1,2,4,8,16,32,64);
@x = sort(@x); #@x = @x = sort(@x); #@x = (1,16,2,32,4,64,8)(1,16,2,32,4,64,8)
Perl 26
ArraysArrays
chop( ) operatorchop( ) operator@x = ("bill\n", "frank\n");@x = ("bill\n", "frank\n");
chop(@x); # @x = ("bill", "frank")chop(@x); # @x = ("bill", "frank")
Perl 27
ArraysArrays
Scalar and array contextsScalar and array contexts– Operator expecting an operand to be Operator expecting an operand to be
scalar is being evaluated in scalar is being evaluated in scalar scalar contextcontext
– Operator expecting an operand to be Operator expecting an operand to be an array is being evaluated in an array is being evaluated in array array contextcontext
Perl 28
ArraysArrays
Scalar and array contextsScalar and array contexts– Concatenating a null string to an Concatenating a null string to an
expression forces it to be evaluated in expression forces it to be evaluated in scalar contextscalar context@x = ("x", "y", "z");@x = ("x", "y", "z");
print ("There are ",@x, " elements\n"); # print ("There are ",@x, " elements\n"); # prints "xyz" for @xprints "xyz" for @x
print ("There are ", "".@x, " elements\n"); print ("There are ", "".@x, " elements\n"); # prints 3 for @x# prints 3 for @x
Perl 29
ArraysArrays
<STDIN> as an array<STDIN> as an array– In scalar context, <STDIN> returns next In scalar context, <STDIN> returns next
line of inputline of input– In array context, <STDIN> returns all the In array context, <STDIN> returns all the
remaining lines of input up to the end of fileremaining lines of input up to the end of file Each line returned as a separate element of listEach line returned as a separate element of list
@x = <STDIN>@x = <STDIN>If user types 4 lines, then presses control-D (to If user types 4 lines, then presses control-D (to indicate end-of-file), the array has 4 elementsindicate end-of-file), the array has 4 elements
Perl 30
Control StructuresControl Structures
Statement blocksStatement blocks{{
first_statement;first_statement;
……
last_statement;last_statement;
}}
Perl 31
Control StructuresControl Structures
if/unless statementif/unless statement
if (expression) {if (expression) {
first_true_statement;first_true_statement;
……
last_true_statement;last_true_statement;
}}
Perl 32
Control StructuresControl Structures
if/unless statementif/unless statement if (expression) {if (expression) {
first_true_statement;first_true_statement;……last_true_statement;last_true_statement;
} else {} else {first_false_statement;first_false_statement;……last_false_statement;last_false_statement;
}}
Perl 33
Control StructuresControl Structures if/unless statementif/unless statement
if (expression_one) {if (expression_one) {one_true_statement_first;one_true_statement_first;……one_true_statement_last;one_true_statement_last;} elseif (expression_two) {} elseif (expression_two) {two_true_statement_first;two_true_statement_first;……two_true_statement_last;two_true_statement_last;} elseif (expression_three) {} elseif (expression_three) {three_true_statement_first;three_true_statement_first;……three_true_statement_last;three_true_statement_last;} else {} else {false_statement_first;false_statement_first;……false_statement_last;false_statement_last;}}
Perl 34
Control StructuresControl Structures
if/unless statementif/unless statement
unless (expression) {unless (expression) {
statement_one;statement_one;
} else {} else {
statement_two;statement_two;
}}
Perl 35
Control StructuresControl Structures
These expressions are the only These expressions are the only ones which evaluate to falseones which evaluate to false– """"– ( )( )– "0""0"– undefundef– 00
Perl 36
Control StructuresControl Structures
while/until statementwhile/until statementwhile (expression) {while (expression) {
statement_first;statement_first;
……
statement_last;statement_last;
}}
Perl 37
Control StructuresControl Structures
while/until statementwhile/until statementuntil (expression) {until (expression) {
statement_first;statement_first;
……
statement_last;statement_last;
}}
Perl 38
Control StructuresControl Structures
for statementfor statementfor (initial_exp; test_exp; for (initial_exp; test_exp;
increment_exp) {increment_exp) {
statement_first;statement_first;
……
statement_last;statement_last;
}}
Perl 39
Control StructuresControl Structures
for statementfor statementinitial_exp;initial_exp;
while (test_exp) {while (test_exp) {
statement_first;statement_first;
……
statement_last;statement_last;
increment_exp;increment_exp;
}}
Perl 40
Control StructuresControl Structures
foreach statementforeach statementforeach $a (@some_list) {foreach $a (@some_list) {
statement_first;statement_first;
……
statement_last;statement_last;
}}
Perl 41
Control StructuresControl Structures
foreach statementforeach statement@x = (1,2,3,4,5);@x = (1,2,3,4,5);
foreach $y (reverse @x) {foreach $y (reverse @x) {
print $y;print $y;
} # prints 54321} # prints 54321
Perl 42
Control StructuresControl Structures
foreach statementforeach statement– If scalar variable is missing, $_ is If scalar variable is missing, $_ is
assumed assumed
@x = (1,2,3,4,5);@x = (1,2,3,4,5);
foreach (reverse @x) {foreach (reverse @x) {
print;print;
} # prints 54321} # prints 54321
Perl 43
Associative ArraysAssociative Arrays
List of items indexed by arbitrary List of items indexed by arbitrary scalars, called scalars, called keyskeys
%x is array%x is array {$key} is index{$key} is index
$x{"Bill"} = 45.67;$x{"Bill"} = 45.67; $x{45.56} = "fred";$x{45.56} = "fred";
Perl 44
Associative ArraysAssociative Arrays
Literal representationLiteral representation@x_list = %x; # x_list = ("Bill", @x_list = %x; # x_list = ("Bill", 45.67, 45.56, "fred") or (45.56, "fred", 45.67, 45.56, "fred") or (45.56, "fred", "Bill", 45.67)"Bill", 45.67)
%y = @x_list;%y = @x_list;
%y = %x;%y = %x;
%y = ("Bill", 45.67, 45.56, "fred");%y = ("Bill", 45.67, 45.56, "fred");
Perl 45
Associative ArraysAssociative Arrays
keys( ) operatorkeys( ) operator@z = keys(%x); # @z=("Bill",45.56) @z = keys(%x); # @z=("Bill",45.56) or or (45.56, "Bill")(45.56, "Bill")
values( ) operatorvalues( ) operator@z = values(%x); # @z=(45.67, @z = values(%x); # @z=(45.67, "fred") "fred") or ("fred",45.67)or ("fred",45.67)
Perl 46
Associative ArraysAssociative Arrays
each( ) operatoreach( ) operator– each (%array) returns the nextkey-value each (%array) returns the nextkey-value
pairpair
while (($first,$last) = each(%last)) {while (($first,$last) = each(%last)) {
print "The last name of $first is print "The last name of $first is $last\n"$last\n"
delete( ) operatordelete( ) operator%x = ("aa", "bb", 5.6, 8.77);%x = ("aa", "bb", 5.6, 8.77);
delete $x{"aa"}delete $x{"aa"}
Perl 47
Basic I/OBasic I/O
Input from <STDIN>Input from <STDIN>while ($_ = <STDIN>) {while ($_ = <STDIN>) {chop $_;chop $_;……}}
while (<STDIN>) {while (<STDIN>) {chop;chop;……}}
Perl 48
Basic I/OBasic I/O
Input from the diamond operator <>Input from the diamond operator <>– Gets data from files specified on the Gets data from files specified on the
command line that invoked given Perl command line that invoked given Perl programprogram If no files on command line, the diamond If no files on command line, the diamond
operator reads from standard inputoperator reads from standard input
while (<>) {while (<>) {
print $_;print $_;
}}
Perl 49
Basic I/OBasic I/O
Input from the diamond operator <>Input from the diamond operator <>– Actually, diamond operator gets its input Actually, diamond operator gets its input
by examining @ARGV, the array which is a by examining @ARGV, the array which is a list of command line argumentslist of command line arguments Can set this array in programCan set this array in program
@ARGV = ("aa", "bb", "cc");@ARGV = ("aa", "bb", "cc");
while (<>) { # processes files aa, bb, and ccwhile (<>) { # processes files aa, bb, and cc
print "This line of the file is: $_";print "This line of the file is: $_";
}}
Perl 50
Basic I/OBasic I/O
Output to STDOUTOutput to STDOUT– print operatorprint operator
Argument is a list of stringsArgument is a list of strings Return value is true or false, depending Return value is true or false, depending
on success of the outputon success of the output
$x = print("Hello", " world", "\n");$x = print("Hello", " world", "\n");
– Formatted outputFormatted outputprintf "%9s %4d %12.5f\n", $s, $n, $r;printf "%9s %4d %12.5f\n", $s, $n, $r;
Perl 51
Regular ExpressionsRegular Expressions
Enclosed in-between slashesEnclosed in-between slashes Checking for occurrence in $_Checking for occurrence in $_
if (/abc/) {if (/abc/) {print $_;print $_;
}}while (<>) {while (<>) {
if (/ab*c/) {if (/ab*c/) {print $_;print $_;
}}}}
Perl 52
Regular ExpressionsRegular Expressions
Single-character patternsSingle-character patterns– A single character matches itselfA single character matches itself– The dot . matches any single The dot . matches any single
character except the newline (\n)character except the newline (\n)
Perl 53
Regular ExpressionsRegular Expressions
Single-character patternsSingle-character patterns– A character class is represented by a A character class is represented by a
list of characters enclosed between [ ]list of characters enclosed between [ ] For the pattern to match, one and only For the pattern to match, one and only
one of these characters must be presentone of these characters must be present [abcde][abcde] [aeiouAEIOU][aeiouAEIOU] [0-9][0-9] [a-zA-Z0-9][a-zA-Z0-9]
Perl 54
Regular ExpressionsRegular Expressions
Single-character patternsSingle-character patterns– Negated character classNegated character class
[^0-9][^0-9]– Matches any character except a digitMatches any character except a digit
[^aeiouAEIOU][^aeiouAEIOU]– Matches any single non-vowelMatches any single non-vowel
Perl 55
Regular ExpressionsRegular Expressions
Single-character patternsSingle-character patterns– Predefined character classesPredefined character classes
\d\d– digitsdigits– [0-9][0-9]
\D\D– not digitsnot digits– [^0-9][^0-9]
Perl 56
Regular ExpressionsRegular Expressions
Single-character patternsSingle-character patterns– Predefined character classesPredefined character classes
\w\w– wordswords– [a-zA-Z0-9_][a-zA-Z0-9_]
\W\W– not wordsnot words– [^a-zA-Z0-9_][^a-zA-Z0-9_]
\s\s– spacespace– [\r\t\n\f][\r\t\n\f]
\S\S– not spacenot space– [^\r\t\n\f][^\r\t\n\f]
Perl 57
Regular ExpressionsRegular Expressions
Grouping patternsGrouping patterns– SequenceSequence
abcabc matches matches aa followed by followed by bb followed by followed by cc
– MultipliersMultipliers **
– 0 or more0 or more ++
– 1 or more1 or more ??
– 0 or 10 or 1
Perl 58
Regular ExpressionsRegular Expressions
Grouping patternsGrouping patterns– MultipliersMultipliers
{n,m}{n,m}– Between n and m occurrences inclusiveBetween n and m occurrences inclusive
{n,}{n,}– At least n occurrencesAt least n occurrences
{n}{n}– Exactly n occurrencesExactly n occurrences
Thus, * is {0,}, + is {1,}, and ? is {0,1}Thus, * is {0,}, + is {1,}, and ? is {0,1}
Perl 59
Regular ExpressionsRegular Expressions
– AlternationAlternation /bill|fred//bill|fred/ /a|b|c/ is the same as /[abc]//a|b|c/ is the same as /[abc]/
Perl 60
Regular ExpressionsRegular Expressions
– All matching is greedyAll matching is greedy Longest expression matches firstLongest expression matches first In "a yyy c yyyyyyyy c yyy d", the pattern In "a yyy c yyyyyyyy c yyy d", the pattern
"a.*c.*d" induces a match of the first ".*" "a.*c.*d" induces a match of the first ".*" on " yyy c yyyyyyyy "on " yyy c yyyyyyyy "
Consider the pattern "a.*cx.*d" matching Consider the pattern "a.*cx.*d" matching the string "a yyy cx yyyyyyyy cy yyy d"the string "a yyy cx yyyyyyyy cy yyy d"
– The first ".*" first matches the substring " yyy The first ".*" first matches the substring " yyy cx yyyyyyyy ", and then backtracking occurscx yyyyyyyy ", and then backtracking occurs
Perl 61
Regular ExpressionsRegular Expressions
– Parentheses as memoryParentheses as memory Parentheses around a pattern causes the Parentheses around a pattern causes the
part of the string which matches this part of the string which matches this pattern to be remembered, so that it can pattern to be remembered, so that it can be later referencedbe later referenced
Consider /bill(.)fred\1/ versus /bill.fred./Consider /bill(.)fred\1/ versus /bill.fred./ /a(.)b(.)c\2d\1//a(.)b(.)c\2d\1/ /a(.*)b\1c//a(.*)b\1c/
Perl 62
Regular ExpressionsRegular Expressions
Anchoring patternsAnchoring patterns– Normally, beginning of pattern is Normally, beginning of pattern is
shifted through the string from left to shifted through the string from left to rightright
– Anchoring ensures that parts of the Anchoring ensures that parts of the pattern match with particular parts of pattern match with particular parts of the stringthe string
Perl 63
Regular ExpressionsRegular Expressions
Anchoring patternsAnchoring patterns– \b requires a word boundary at the given \b requires a word boundary at the given
spot in order for the pattern to matchspot in order for the pattern to match Word boundary is place between \w and \W or Word boundary is place between \w and \W or
between \w and the start or end of the stringbetween \w and the start or end of the string– /car\b/ matches car but not cars/car\b/ matches car but not cars– /\bbarb/ matches "barb" and "barbara", but not /\bbarb/ matches "barb" and "barbara", but not
"ebarb""ebarb"– /\bport\b/ matches "port", but neither "sport" nor /\bport\b/ matches "port", but neither "sport" nor
"ports""ports"
Perl 64
Regular ExpressionsRegular Expressions
Anchoring patternsAnchoring patterns– \B requires that there not be a word \B requires that there not be a word
boundaryboundary /\bFred\B/ matches "Frederick" but not "Fred /\bFred\B/ matches "Frederick" but not "Fred
Flintstone"Flintstone"
– The caret (^) matches the beginning of The caret (^) matches the beginning of the string if it makes sensethe string if it makes sense /^a/ matches "a" if it is the first character of /^a/ matches "a" if it is the first character of
the stringthe string /a^/ matches "a^" anywhere in the string/a^/ matches "a^" anywhere in the string
Perl 65
Regular ExpressionsRegular Expressions
Anchoring patternsAnchoring patterns– The dollar sign ($) matches the end of The dollar sign ($) matches the end of
the string if it makes sensethe string if it makes sense
Perl 66
Regular ExpressionsRegular Expressions
PrecedencePrecedence– ParenthesesParentheses
( )( )
– MultipliersMultipliers + * ? {n,m}+ * ? {n,m}
– Sequence and anchoringSequence and anchoring abc ^ $ \b \Babc ^ $ \b \B
– AlternationAlternation ||
Perl 67
Regular ExpressionsRegular Expressions
Selecting a different targetSelecting a different target– Want to match a variable other than $_Want to match a variable other than $_– The operator =~ matches the left-hand The operator =~ matches the left-hand
argumentargument$a = "hello world";$a = "hello world";$a =~ /^he/; # true$a =~ /^he/; # true$a =~ /(.)\1/; # true, matches the $a =~ /(.)\1/; # true, matches the
double ldouble l if ($a =~ /(.)\1/) { # trueif ($a =~ /(.)\1/) { # true
……}}
Perl 68
Regular ExpressionsRegular Expressions
Selecting a different targetSelecting a different targetif (<STDIN> =~ /^[yY]/) {if (<STDIN> =~ /^[yY]/) {
……
}}
if (<STDIN> =~ /^y/i) { # i ignores caseif (<STDIN> =~ /^y/i) { # i ignores case
……
}}
Perl 69
Regular ExpressionsRegular Expressions
Using a different delimiterUsing a different delimiter– If regular expression contains "/", If regular expression contains "/",
precede it with a "\"precede it with a "\"
$path = <STDIN>;$path = <STDIN>;
if ($path =~ /^\/usr\/etc/) if ($path =~ /^\/usr\/etc/) {{
……
}}
Perl 70
Regular ExpressionsRegular Expressions
Using a different delimiterUsing a different delimiter$path = <STDIN>;$path = <STDIN>;
if ($path =~ if ($path =~ m#^/usr/etc#) {m#^/usr/etc#) {
……
}}
Perl 71
Regular ExpressionsRegular Expressions
Using variable interpolationUsing variable interpolation$what = "is";$what = "is";
$sentence = "This is good.";$sentence = "This is good.";
if ($sentence =~ /\b$what\b/) {if ($sentence =~ /\b$what\b/) {
print "This sentence print "This sentence contains the contains the word word $what.\n"$what.\n"
}}
Perl 72
Regular ExpressionsRegular Expressions
Special read-only variablesSpecial read-only variables– After successful match, $1, $2, … are After successful match, $1, $2, … are
set to same values as \1, \2, …set to same values as \1, \2, …
$_ = "This is good";$_ = "This is good";
/(\w+)\W+(\w+)/; # matches /(\w+)\W+(\w+)/; # matches first two first two wordswords
# $1 is "This" and $2 is "is"# $1 is "This" and $2 is "is"
Perl 73
Regular ExpressionsRegular Expressions
Special read-only variablesSpecial read-only variables$_ = "This is good";$_ = "This is good";
($first,$second) = /(\w+)\W+(\($first,$second) = /(\w+)\W+(\w+)/;w+)/;
# $first is "This" and $second is # $first is "This" and $second is "is""is"
Perl 74
Regular ExpressionsRegular Expressions
Special read-only variablesSpecial read-only variables– $& is the part of the string that $& is the part of the string that
matches the regular expressionmatches the regular expression– $` is the part of the string before the $` is the part of the string before the
part that matched the regular part that matched the regular expressionexpression
– $' is the part of the string after the $' is the part of the string after the part that matched the regular part that matched the regular expressionexpression
Perl 75
Regular ExpressionsRegular Expressions
Special read-only variablesSpecial read-only variables$_ = "this is a sample string";$_ = "this is a sample string";
/sa.*le/; # matches "sample"/sa.*le/; # matches "sample"
# $` is "this is a "# $` is "this is a "
# $& is "sample"# $& is "sample"
# $' is " string"# $' is " string"
Perl 76
Regular ExpressionsRegular Expressions
SubstitutionsSubstitutions– s/regular_expression/replacement_string/s/regular_expression/replacement_string/– Replaces first occurrenceReplaces first occurrence
$_ = "bill yyyyyyy fred";$_ = "bill yyyyyyy fred";
s/y*/tom/; # $_ is now "bill tom fred"s/y*/tom/; # $_ is now "bill tom fred"– Flag "g" substitutes all occurrencesFlag "g" substitutes all occurrences
$_ = "foot fool buffoon";$_ = "foot fool buffoon";
s/foo/bar/g; # $_ is now "bart barl s/foo/bar/g; # $_ is now "bart barl bufbarn"bufbarn"
Perl 77
Regular ExpressionsRegular Expressions
SubstitutionsSubstitutions$_ = "hello world";$_ = "hello world";
$new = "goodbye";$new = "goodbye";
s/hello/$new/; # $_ is now s/hello/$new/; # $_ is now "goodbye "goodbye world"world"
Perl 78
Regular ExpressionsRegular Expressions
SubstitutionsSubstitutions$_ = "this is a test";$_ = "this is a test";
s/(\w+)/<$1>/g; # $_ is now s/(\w+)/<$1>/g; # $_ is now "<this> <is> <a> <test>""<this> <is> <a> <test>"
$x[$j] =~ s/here/there/;$x[$j] =~ s/here/there/;
$d{"abc"} =~ s/there/here/;$d{"abc"} =~ s/there/here/;
Perl 79
Regular ExpressionsRegular Expressions
split( ) operatorsplit( ) operator– Takes as arguments a regular Takes as arguments a regular
expression and a string, looks for all expression and a string, looks for all occurrences of the regular expression occurrences of the regular expression in the string, and the parts of the in the string, and the parts of the string that don’t match the regular string that don’t match the regular expression are returned in sequence expression are returned in sequence as a list of valuesas a list of values
Perl 80
Regular ExpressionsRegular Expressions
split( ) operatorsplit( ) operator$line="67;bill;;/usr/bin;joe";$line="67;bill;;/usr/bin;joe";
@fields=split(/;/,$line);@fields=split(/;/,$line);
# @fields is # @fields is ("67","bill","","/usr/bin","joe")("67","bill","","/usr/bin","joe")
@fields=split(/;+/,$line);@fields=split(/;+/,$line);
# @fields is ("67", "bill", "/usr/bin", # @fields is ("67", "bill", "/usr/bin", "joe")"joe")
Perl 81
Regular ExpressionsRegular Expressions
split( ) operatorsplit( ) operator– split(/regex/)split(/regex/) is the same as is the same as
split(/regex/,$_)split(/regex/,$_)– splitsplit is the same as is the same as split(/\s+/,$_)split(/\s+/,$_)
Perl 82
Regular ExpressionsRegular Expressions
join ( ) operatorjoin ( ) operator– Inverse of split( )Inverse of split( )– Takes a list of values and puts them Takes a list of values and puts them
together with a separator element together with a separator element between each pair of itemsbetween each pair of items
$line = join(";",@fields); # see $line = join(";",@fields); # see previous previous slidesslides
Perl 83
FunctionsFunctions
Defining a functionDefining a functionsub repeat {sub repeat {
print "Hello, $word\n"print "Hello, $word\n"}}
– Subroutine definitions can be anywhere in Subroutine definitions can be anywhere in program textprogram text
– Subroutine definitions are globalSubroutine definitions are global For two subroutines with same name, the For two subroutines with same name, the
latter one overrides the former onelatter one overrides the former one
– By default, any variable reference inside a By default, any variable reference inside a subroutine is globalsubroutine is global
Perl 84
FunctionsFunctions
Invoking a functionInvoking a function– &repeat;&repeat;– $x = 5+&repeat;$x = 5+&repeat;
Return ValuesReturn Values– Return value of a subroutine is the value Return value of a subroutine is the value
of the logically last expression evaluatedof the logically last expression evaluatedsub sum_of_a_and_b {sub sum_of_a_and_b {
$a+$b;$a+$b;
}}
Perl 85
FunctionsFunctions
Return valuesReturn values$a=7; $b=8;$a=7; $b=8;$x=3*&sum_of_a_and_b;$x=3*&sum_of_a_and_b;
sub list_of_a_and_b {sub list_of_a_and_b {($a,$b);($a,$b);
}}
$a=7; $b=8;$a=7; $b=8;@x=&list_of_a_and_b;@x=&list_of_a_and_b;
Perl 86
FunctionsFunctions
Return valuesReturn valuessub a_or_b {sub a_or_b {
if ($a>0) {if ($a>0) {print "Write a: $a\n";print "Write a: $a\n";$a;$a;
} else {} else {print "Write b: $b\n";print "Write b: $b\n";$b;$b;
}}}}
Perl 87
FunctionsFunctions
ArgumentsArguments– Invoking a subroutine with arguments Invoking a subroutine with arguments
in parentheses puts these arguments in parentheses puts these arguments into a list denoted by @_ for the into a list denoted by @_ for the duration of the subroutineduration of the subroutine
Perl 88
FunctionsFunctions
ArgumentsArgumentssub say {sub say {
print "$_[0], $_[1]!\n";print "$_[0], $_[1]!\n";
} }
&say("goodbye", "cruel world");&say("goodbye", "cruel world");
&say("hello", "world");&say("hello", "world");
Perl 89
FunctionsFunctions
ArgumentsArguments– @_ is local to the subroutine@_ is local to the subroutine
sub add {sub add {$sum = 0;$sum = 0;foreach $_ (@_) {foreach $_ (@_) {
$sum += $_;$sum += $_;}}$sum;$sum;
}}
$a = &add(4,5,6); # adds 4, 5, 6 and assigns 15 to $a$a = &add(4,5,6); # adds 4, 5, 6 and assigns 15 to $aprint &add(6,7,8,9);print &add(6,7,8,9);print &add(6..9);print &add(6..9);
Perl 90
FunctionsFunctions
Local VariablesLocal Variablessub bigger_than {sub bigger_than {
local($n,@values);local($n,@values);($n,@values) = @_; # or local($n,@values) ($n,@values) = @_; # or local($n,@values) =@_=@_local(@result);local(@result);foreach $_ (@values) {foreach $_ (@values) {if ($_ > $n) {if ($_ > $n) {push(@result,$_);push(@result,$_);}}}}@result;@result;
}}
Perl 91
FunctionsFunctions
Local variablesLocal variables@new=&bigger_than(100,@list); @new=&bigger_than(100,@list);
#@new #@new gets elements of @list > gets elements of @list > 100100
@x = &bigger_than(5,1,5,15,67); @x = &bigger_than(5,1,5,15,67); #@x= #@x= (15, 67)(15, 67)
Perl 92
Miscellaneous Control Miscellaneous Control StructuresStructures
lastlast– Exits a loopExits a loop
nextnext– Begins another loop iterationBegins another loop iteration
redoredo– Jumps to the top of a loop without Jumps to the top of a loop without
beginning another iterationbeginning another iteration
Perl 93
Miscellaneous Control Miscellaneous Control StructuresStructures
@movies = ("Star Wars", "Porky's", "Rocky @movies = ("Star Wars", "Porky's", "Rocky 5", "Terminator", "Babe”);5", "Terminator", "Babe”);
@ratings = ("PG", "R", "PG-13", "R", "G");@ratings = ("PG", "R", "PG-13", "R", "G");
for ($j=0, $j<=4, $j++) {for ($j=0, $j<=4, $j++) {next if $ratings[$j] eq 'R';next if $ratings[$j] eq 'R';print "Would you like to see $movie[$j]?";print "Would you like to see $movie[$j]?";chop($answer = <>);chop($answer = <>);last if $answer eq 'yes';last if $answer eq 'yes';
}}if ($answer eq 'yes') {print "That will be \if ($answer eq 'yes') {print "That will be \
$4.25\n"}$4.25\n"}else {print "Sorry you don't see anything you else {print "Sorry you don't see anything you
like.\n"}like.\n"}
Perl 94
Miscellaneous Control Miscellaneous Control StructuresStructures
print "Type in 4 digits (0 through 9)\n\n"print "Type in 4 digits (0 through 9)\n\n"
for ($j=1; $j<=4; $j++) {for ($j=1; $j<=4; $j++) {
print "Choice $j:";print "Choice $j:";
chop($digit[$j] = <>);chop($digit[$j] = <>);
redo if $digit[$j] > 9;redo if $digit[$j] > 9;
redo if $digit[$j] < 0;redo if $digit[$j] < 0;
}}
print "Your choices: @digit \n";print "Your choices: @digit \n";
Perl 95
Miscellaneous Control Miscellaneous Control StructuresStructures
Labelled BlocksLabelled BlocksOUTER: for ($i=1; $i<=10; $i++) {OUTER: for ($i=1; $i<=10; $i++) {
INNER: for ($j=1; $j<=10; $j++) {INNER: for ($j=1; $j<=10; $j++) {if ($i*$j == 25) {if ($i*$j == 25) {
print "$i times $j is 25!\n";print "$i times $j is 25!\n";last OUTER;last OUTER;
}}if ($j > $i) {if ($j > $i) {
next OUTER;next OUTER;}}
}}}}
Perl 96
Miscellaneous Control Miscellaneous Control StructuresStructures
Expression ModifiersExpression Modifiers– exp2 if exp1; # if (exp1) {exp2;}exp2 if exp1; # if (exp1) {exp2;}– exp2 unless exp1; # unless (exp1) exp2 unless exp1; # unless (exp1)
{exp2;}{exp2;}– exp2 while exp1; # while (exp1) exp2 while exp1; # while (exp1)
{exp2;}{exp2;}– exp2 until exp1; # until (exp1) exp2 until exp1; # until (exp1)
{exp2;}{exp2;}
Perl 97
Miscellaneous Control Miscellaneous Control StructuresStructures
&&, ||, and ?: as control structures&&, ||, and ?: as control structures– exp1 && exp2exp1 && exp2
if (exp1) {exp2;}if (exp1) {exp2;}
– exp1 || exp2exp1 || exp2 unless (exp1) {exp2;}unless (exp1) {exp2;}
– exp1 ? exp2 : exp3;exp1 ? exp2 : exp3; if (exp1) {exp2;} else {exp3;}if (exp1) {exp2;} else {exp3;}
Perl 98
Filehandles and File TestsFilehandles and File Tests
FilehandlesFilehandles– I/O connection nameI/O connection name– STDINSTDIN– STDOUTSTDOUT– STDERRSTDERR
Perl 99
Filehandles and File TestsFilehandles and File Tests
Opening and closing a filehandleOpening and closing a filehandle– open(FILEHANDLE, "external_file_name")open(FILEHANDLE, "external_file_name")
Opens file for readingOpens file for reading
– open(FILEHANDLE, open(FILEHANDLE, ">external_file_name")">external_file_name") Opens file for writingOpens file for writing
– open(FILEHANDLE, open(FILEHANDLE, ">>external_file_name")">>external_file_name") Opens file for appendingOpens file for appending
Perl 100
Filehandles and File TestsFilehandles and File Tests
Opening and closing a filehandleOpening and closing a filehandle– close(FILEHANDLE)close(FILEHANDLE)
Closes fileCloses file
– These operations return true or false, These operations return true or false, depending on whether or not the depending on whether or not the operation was successfuloperation was successful
– A filehandle that hasn’t been successfully A filehandle that hasn’t been successfully opened can be read (you get the end-of-opened can be read (you get the end-of-file at the start) or written to (data file at the start) or written to (data disappears)disappears)
Perl 101
Filehandles and File TestsFilehandles and File Tests
Opening and closing a filehandleOpening and closing a filehandle– The die( ) operator prints out its The die( ) operator prints out its
arguments on STDERR and then ends arguments on STDERR and then ends the processthe process
unless (open(FILE, ">/x/y/data")) {unless (open(FILE, ">/x/y/data")) {die "File couldn't be opened\n";die "File couldn't be opened\n";
}}
open(FILE, ">/x/y/data") || die “File open(FILE, ">/x/y/data") || die “File couldn’t couldn’t be opened\n”;be opened\n”;
Perl 102
Filehandles and File TestsFilehandles and File Tests
Using filehandlesUsing filehandlesopen(IN,"$a") || die "Cannot open $a for open(IN,"$a") || die "Cannot open $a for
reading";reading";
open(OUT, ">$b") || "Cannot create $b";open(OUT, ">$b") || "Cannot create $b";
while (<IN>) {while (<IN>) {
print OUT $_;print OUT $_;
}}
close(IN);close(IN);
close(OUT);close(OUT);
Perl 103
Filehandles and File TestsFilehandles and File Tests
File testsFile testsprint "What file? ";print "What file? ";$filename=<STDIN>;$filename=<STDIN>;chop($filename);chop($filename);if (-r $filename && -w $filename) {if (-r $filename && -w $filename) {
# file exists and I can read and write it# file exists and I can read and write it……
}}
Perl 104
Filehandles and File TestsFilehandles and File Tests
File testsFile tests– -x-x
File is executableFile is executable
– -e-e File or directory existsFile or directory exists
– -o-o File or directory is owned by userFile or directory is owned by user
Perl 105
Filehandles and File TestsFilehandles and File Tests
File testsFile tests– -z-z
File exists and has zero sizeFile exists and has zero size
– -s-s File or directory exists and has nonzero sizeFile or directory exists and has nonzero size
– Return value is the size in bytesReturn value is the size in bytes
– -f-f Entry is a fileEntry is a file
– -d-d Entry is a directoryEntry is a directory
Perl 106
Filehandles and File TestsFilehandles and File Tests
stat( ) operatorstat( ) operator– stat(FILEHANDLE)stat(FILEHANDLE)
Returns 13-element array, where Returns 13-element array, where stat(FILEHANDLE)[7] is the size of the file stat(FILEHANDLE)[7] is the size of the file in bytesin bytes
Perl 107
FormatsFormats
Defining a FormatDefining a Formatformat ADDRESSLABEL =format ADDRESSLABEL ===========================================================| @<<<<<<<<<<<<<<<<<<<<<<<<<< || @<<<<<<<<<<<<<<<<<<<<<<<<<< |$name$name| @<<<<<<<<<<<<<<<<<<<<<<<<<< || @<<<<<<<<<<<<<<<<<<<<<<<<<< |$address$address| @<<<<<<<<<<<<<<<<, @< @<<<< || @<<<<<<<<<<<<<<<<, @< @<<<< |$city, $state, $zip$city, $state, $zip==========================================================..
Perl 108
FormatsFormats
Invoking a FormatInvoking a Formatopen(ADDRESSLABEL, ">labels") | | die "Can’t open(ADDRESSLABEL, ">labels") | | die "Can’t
create";create";
open(ADDRESSES, "addresses") | | die "Can’t open(ADDRESSES, "addresses") | | die "Can’t open addresses";open addresses";
while (<ADDRESSES>) {while (<ADDRESSES>) {
($name,$address,$city,$state,$zip) = split(/:/);($name,$address,$city,$state,$zip) = split(/:/);
write ADDRESSLABEL; # This is filehandlewrite ADDRESSLABEL; # This is filehandle
# by default, format of same name is also used# by default, format of same name is also used
}}
Perl 109
FormatsFormats
Text FieldsText Fields– @<<<<@<<<<
5 spaces left-justified5 spaces left-justified
– @>>>@>>> 4 spaces right-justified4 spaces right-justified
– @| | | | |@| | | | | 6 spaces centered6 spaces centered
Numeric FieldsNumeric Fields– @###.##@###.##
Perl 110
FormatsFormats
sprintf operatorsprintf operator– Returns as a string whatever printf Returns as a string whatever printf
would have printedwould have printedformat MONEY =format MONEY =
Assets: @<<<<<<<<< Liabilities Assets: @<<<<<<<<< Liabilities @<<<<<<<< Net: @<<<<<<<<<@<<<<<<<< Net: @<<<<<<<<<
$func($assets,10), &func($liab,9), $func($assets,10), &func($liab,9), $func($assets - $liab,10)$func($assets - $liab,10)
..
Perl 111
FormatsFormats
sprintf operatorsprintf operatorsub func {sub func {
local($n, $width) = @_;local($n, $width) = @_;$width - = 2;$width - = 2;$n = sprintf("%.2f", $n);$n = sprintf("%.2f", $n);if ($n < 0) {if ($n < 0) {
sprintf("[%$width.2f]", -$n);sprintf("[%$width.2f]", -$n);} else {} else {
sprintf(" %$width.2f ", $n);sprintf(" %$width.2f ", $n);}}
}}
Perl 112
FormatsFormats
Multiline fieldsMultiline fieldsformat STDOUT =format STDOUT =Text before.Text before.@*@*$long_string$long_stringText after.Text after...
$long_string = "Bill\nFred\nSue\nTom\n";$long_string = "Bill\nFred\nSue\nTom\n";write;write;
Perl 113
FormatsFormats
Multiline fieldsMultiline fieldsText before.Text before.BillBillFredFredSueSueTomTomText after.Text after.
Perl 114
FormatsFormats
Filled fieldsFilled fields– Allows one to create a paragraph Allows one to create a paragraph
where words are broken at word where words are broken at word boundaries and lines are wrapped as boundaries and lines are wrapped as neededneeded
– Substitute ^ for @Substitute ^ for @
Perl 115
FormatsFormats Filled fieldsFilled fields
format try =format try =Name: @<<<<<<<<< Comment: Name: @<<<<<<<<< Comment:
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$name, $comment$name, $comment
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$comment$comment
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$comment$comment. .
– $comment is changed each time to what is not $comment is changed each time to what is not yet printedyet printed
Perl 116
FormatsFormats
Filled fieldsFilled fieldsformat try =format try =Name: @<<<<<<<<< Comment: Name: @<<<<<<<<< Comment:
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$name, $comment$name, $comment~ ~
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$comment$comment~ ~
^<<<<<<<<<<<<<^<<<<<<<<<<<<<$comment$comment..
– ~ suppresses line if only blanks would print~ suppresses line if only blanks would print
Perl 117
FormatsFormats
Filled fieldsFilled fieldsformat try =format try =
Name: @<<<<<<<<< Comment: Name: @<<<<<<<<< Comment: ^<<<<<<<<<<<<<^<<<<<<<<<<<<<
$name, $comment$name, $comment
~~ ~~ ^<<<<<<<<<<<<<^<<<<<<<<<<<<<
$comment$comment
..– ~~ repeats this line until nothing but blanks ~~ repeats this line until nothing but blanks
are leftare left
Perl 118
FormatsFormats
Changing the FilehandleChanging the Filehandleprint "Hello world\n"; # prints to STDOUTprint "Hello world\n"; # prints to STDOUT
select(LOGFILE); # select a new filehandleselect(LOGFILE); # select a new filehandle
print "Hello world\n"; # prints to LOGFILEprint "Hello world\n"; # prints to LOGFILE
– The return value from select( ) is the The return value from select( ) is the name of the old filehandlename of the old filehandle$oldhandle = select(LOGFILE);$oldhandle = select(LOGFILE);
print "This goes to LOGFILE\n";print "This goes to LOGFILE\n";
select($oldhandle); # restores the previous select($oldhandle); # restores the previous filehandlefilehandle
Perl 119
FormatsFormats
Changing the Format NameChanging the Format Name– Default format name for a filehandle is Default format name for a filehandle is
the same as the filehandlethe same as the filehandle– Contained in variable $~Contained in variable $~– Set format for REPORT filehandle to Set format for REPORT filehandle to
NEWNEW$oldhandle = select(REPORT);$oldhandle = select(REPORT);
$~ = "NEW";$~ = "NEW";
select($oldhandle);select($oldhandle);
Perl 120
Data TransformationsData Transformations
Finding a substringFinding a substring– $y = index($string, $substring);$y = index($string, $substring);
Scans from left-to-rightScans from left-to-right
$y = index("car", "a"); # $y is 1$y = index("car", "a"); # $y is 1
$z = "fred";$z = "fred";
$y = index($z, $z); # $y is 0$y = index($z, $z); # $y is 0
$y = index($z, "ed"); # $y is 2$y = index($z, "ed"); # $y is 2
$y = index($z, "car"); # $y is -1$y = index($z, "car"); # $y is -1
Perl 121
Data TransformationsData Transformations
Finding a substringFinding a substring– $x = index($string, $substring, $skip);$x = index($string, $substring, $skip);
Third parameter is the minimum value returned Third parameter is the minimum value returned by indexby index
$where=index("hello world", "l"); # $where is 2$where=index("hello world", "l"); # $where is 2
$where=index("hello world", "l",0); #$where is 2$where=index("hello world", "l",0); #$where is 2
$where=index("hello world", "l",1); #$where is 2$where=index("hello world", "l",1); #$where is 2
$where=index("hello world", "l",3); #$where is 3$where=index("hello world", "l",3); #$where is 3
Perl 122
Data TransformationsData Transformations
Finding a substringFinding a substring– $x = rindex("string", "substring", $x = rindex("string", "substring",
$skip)$skip) Scans right-to-leftScans right-to-left
$x=rindex("hello world", "he"); # $w is 0$x=rindex("hello world", "he"); # $w is 0
$x=rindex("hello world", "l"); # $w is 9$x=rindex("hello world", "l"); # $w is 9
$x=rindex("hello world", "o",6); # $w is 4$x=rindex("hello world", "o",6); # $w is 4
Perl 123
Data TransformationsData Transformations
Extracting and replacing a stringExtracting and replacing a string– $s = substr($string, $start, $length);$s = substr($string, $start, $length);
$x = "hello world!";$x = "hello world!";
$y = substr($x, 3, 2); # $y is "lo"$y = substr($x, 3, 2); # $y is "lo"
$y = substr($x, 6, 400); # $y is "world!"$y = substr($x, 6, 400); # $y is "world!"
$z = substr(“10000000000”, 0, $power+1)$z = substr(“10000000000”, 0, $power+1)
– If length < 0, the empty string is If length < 0, the empty string is returnedreturned
Perl 124
Data TransformationsData Transformations
Extracting and replacing a stringExtracting and replacing a string– $start can be less than zero$start can be less than zero
Start that many characters from the rightStart that many characters from the right
$y = substr("This is a string", -3, 3); # $y is $y = substr("This is a string", -3, 3); # $y is "ing""ing"
$y = substr("This is a string", -3, 1); # $y is "i"$y = substr("This is a string", -3, 1); # $y is "i"
– Can omit $lengthCan omit $length Takes entire string from $start positionTakes entire string from $start position
$y = substr("This is a string", 5); # $y is "is a $y = substr("This is a string", 5); # $y is "is a string"string"
Perl 125
Data TransformationsData Transformations
Extracting and replacing a stringExtracting and replacing a string$x = "hello world!";$x = "hello world!";
substr($x, 0, 5) = "hi there"; # $x is "hi substr($x, 0, 5) = "hi there"; # $x is "hi there world!"there world!"
substr($x, -6, 5) = "people"; # $x is "hello substr($x, -6, 5) = "people"; # $x is "hello people!"people!"
Perl 126
Data TransformationsData Transformations
TransliterationTransliteration– Translate one character to anotherTranslate one character to another– Operates by default on $_Operates by default on $_
$_ = "bill and fred";$_ = "bill and fred";
tr/bf/fb/; # $_ is "fill and bred"tr/bf/fb/; # $_ is "fill and bred"
tr/abcde/ABCDE/; # $_ is "fill AnD BrED"tr/abcde/ABCDE/; # $_ is "fill AnD BrED"
tr/a-z/A-Z/; # $_ is "FILL AND BRED"tr/a-z/A-Z/; # $_ is "FILL AND BRED"
tr/A-Z/yx/; # $_ is "xxx yxx xxxx"tr/A-Z/yx/; # $_ is "xxx yxx xxxx"
$_ = "bill and fred";$_ = "bill and fred";
tr/a-z/ABCDE/d; # $_ is "B AD ED" (delete tag)tr/a-z/ABCDE/d; # $_ is "B AD ED" (delete tag)
Perl 127
Data TransformationsData Transformations
TransliterationTransliteration– Return value is number of characters Return value is number of characters
changedchanged$_ = "bill and fred";$_ = "bill and fred";
$count = tr/a-z//; # $_ is unchanged but $count = tr/a-z//; # $_ is unchanged but $count is 11$count is 11
If the second list is empty and there is no If the second list is empty and there is no dd option, then result list is same as the option, then result list is same as the original listoriginal list
Perl 128
Data TransformationsData Transformations TransliterationTransliteration
– Complement Tag Complement Tag Any character in first string is removed from Any character in first string is removed from
set of 256 possible characters and remaining set of 256 possible characters and remaining characters, taken in sequence, form the characters, taken in sequence, form the resulting first stringresulting first string
$_ = "bill and fred";$_ = "bill and fred";$count = tr/a-z//c; # $_ is unchanged, $count $count = tr/a-z//c; # $_ is unchanged, $count
is 2 (non-lowercase letters are counted)is 2 (non-lowercase letters are counted)tr/a-z/_/c; # $_ is "bill_and_fred", non-tr/a-z/_/c; # $_ is "bill_and_fred", non-
lowercase letters are converted to "_"lowercase letters are converted to "_"tr/a-z//cd; # $_ is "billandfred", non-lowercase tr/a-z//cd; # $_ is "billandfred", non-lowercase
letters deletedletters deleted
Perl 129
Data TransformationsData Transformations
TransliterationTransliteration– Squeeze tagSqueeze tag
$_ = "aaabbbcccdefghi";$_ = "aaabbbcccdefghi";
tr/defghi/abcddd/s; # $_ is "aaabbbcccabcd"tr/defghi/abcddd/s; # $_ is "aaabbbcccabcd"
$_ = "bill and fred, jerry and sue";$_ = "bill and fred, jerry and sue";
tr/a-z/X/s; # $_ is "X X X, X X X"tr/a-z/X/s; # $_ is "X X X, X X X"
$_ = "bill and fred, jerry and sue";$_ = "bill and fred, jerry and sue";
tr/a-z/_/cs; # $_ is tr/a-z/_/cs; # $_ is 'bill_and_fred,_jerry_and_sue"'bill_and_fred,_jerry_and_sue"
Perl 130
Data TransformationsData Transformations
TransliterationTransliteration– Other targetsOther targets
$x = "bill and fred";$x = "bill and fred";
$x ~= tr/aeiou/X/; # $x is "bXll Xnd frXd"$x ~= tr/aeiou/X/; # $x is "bXll Xnd frXd"