100 likes | 259 Views
PERL. Just like C but with its own set of quirks. Variables. There is no datatype PERL is loosely typed language Variables take on the data type of the data assigned to them Two forms Scalar: single-valued variable Starts with a $ Array: multi-valued (indexed) variable Starts with a @.
E N D
PERL • Just like C but with its own set of quirks
Variables • There is no datatype • PERL is loosely typed language • Variables take on the data type of the data assigned to them • Two forms • Scalar: single-valued variable • Starts with a $ • Array: multi-valued (indexed) variable • Starts with a @
Scalar Variables • String type (surrounded by single quotes) $var = ‘CATG’; • Floating type $var = 47.235; • Integer type $var = 26;
Scalar String Operations • Search and replace $string = ‘ABC’; $string =~ s/B/b/g; • Note there is no space between the = and the ~ • =~ is the binding operator • Apply the operation on the right to the string on the left • Search and replace a set of characters $string =~ tr/AC/ac/; • Get the length of a string $len = length $string; • Testing for equality if ($string eq ‘ABC’) { # if covered later on
Array Variables • Initialized with a parenthesized list of values • Array of characters @arr = (‘A’, ‘B’, ‘C’); • Array of floating points @arr = (1.3, 2.2, 3.1); • Array of integers @arr = (3, 2, 1);
Array Variables • Print the entire array (no spaces between) print @arr, “\n”; • Print the entire array (spaces between) print “@arr”, “\n”; • Print (access) individual elements print $arr[0], “\n”; • Note the element is a scalar, $
Array Variables • Getting the length of an array $arrLength = scalar @arr; • Remove the last element of an array $last = pop @arr; • Remove the first element of an array $first = shift @arr; • Reverse an array @rev = reverse @arr;
Array Variables • Insert an element splice (@arr, 0, 0, 10); # beginning splice (@arr, 3, 0, 4); # index 3 • Add an element to the beginning unshift (@arr, 6); • Add an element to the end push (@arr, 7); • Combine elements into a single scalar string $allelements = join( ‘’, @arr); # first parameter # is the separater
Homework • Chapter 4, Exercises 4-1 thru 4-5 • Basically, practice all the stuff we did in class • Not to be collected