Sunday, May 12, 2013

Perl Scripting: Part 1

(please click here for introduction)

Perl scripting basics:
Data types
Basic operations
Basic control constructs
List and array

Scalar Data:
-A scalar is the simplest kind of data perl manipulates.
-Perl scalars are either a number or a string of character.
-For perl, a number and a string are treated almost interchangeably.
-Scalar data can be subject to the following:
a. Stored in a scalar variable
b. Can be read from files and devices
c. Can be written out
d. Can be acted on with operators (addition or concatenation) to produce scalar results.

-All perl numbers have the same format internally!
-Perl computes with double precision floating point values.
-There is no concept of integer!
-Floating literals can be either with decimal format or exponential base 10 notation: 1.25 ; 233.00 ;   123.0 ; 2.34e23 ; -34.3E12 ;  -12e-10 (10 to the negative 10th) ;
-Integer literals can be positive or negative:  123 ; -234 ;
-Integers can have base 10 (decimal), Octal (base 8) and hex (base 16):
0377 (leading zero for octal (8))
0xff (leading 0x for hex(16))
0b11111111 (leading 0b for binary)
-The numbers 0377, 0xff, 255, and 255.0 are all the same to perl internally.

-Strings are sequence of characters.
-Strings can be presented in two forms:
a. single-quoted
b. double-quoted

Single quote strings:
Anything within a single quote stands for itself except: ‘\\’ for one backslash; ‘\’ ’ for one single quote (the second backslash followed by two single quotes, not a double quotes).

Double quoted strings:
-Similar to other languages
-Backslash is the leading character for special control sequence.
-Variables within double quoted strings are evaluated with values.

unix> cat
print "Hello World!\n";
print 'Hello World!\n
       line two ';

Hello World!
Hello World!\n
    line two unix>

Scalar Variables:
-An identifier is a name for an object.
-Perl identifier starts with a letter or underscore followed by more letters, digits or underscore.
-Perl identifiers are case sensitive.
-A variable is a name for a container that holds a value.
-A scalar variable holds a single value.
-A perl scalar variable name must be a perl identifier.
-Scalar perl variable always referenced with the leading $.
-Perl scalar variables always contains a $ at the beginning unlike shell or Tcl variables.

$a = 12;
$b = “hello”;
$b = $a + 3;
$b = $b * 2;

-When a string literal is double-quoted, it is subject to variable interpolation.
-Interpolation here means any scalar variable name in the string is replaced with its current value:
$work = “always fun”;
$wife = “not $work”; # $work replaced by always fun.

Operator precedence:
-For those operators that exist in both C and Perl, they share the same precedence and associativity.
-Associativity is used to resolve the order of operation when two operators with the same precedence compete for three operands:

4 ** 3 ** 2    # right associative: 4 ** ( 3 ** 2) = 4 ** 9
16 / 4 * 2     # left associative : ( 16/4) * 2 = 4 * 2

Comparison Operators:
-Perl has two sets of operators for comparing numeric values and strings.

(comparison, operator, string)
equal, ==, eq
not equal, !=, ne
less than, <, lt
greater than, >, gt
less than or equal to, <=, le
greater than or equal to, >=, ge

“if” structure:
-Perl supports “if” and “if” .. “else”.
-Statements must be within “{“ and “}” regardless the number of statements.

if ($name gt ‘hippo’) {
    print “’$name’ comes after ‘hippo’ in sorted order.\n” ;

if ($name gt ‘hippo’) {
    print “’$name’ comes after ‘hippo’ in sorted order.\n” ;
} else {
    print “’$name’ does not come after ‘hippo’.\n” ;
    printf “It could be the same string, in fact.\n” ;

“while” structure:
-The while loop may iterate zero or more times. It iterates as long as the condition is true.

$i = 0;
While ($i < 10) {    $i += 2;
     print “count is now $i\n” ;

Getting user input:
-Perl has a line input operator: <STDIN>
-Each time <STDIN> in a place where a scalar value is expected, perl reads the next complete text line from standard input (until the newline) and uses the string as the value of <STDIN>
-The input contains a end of line in it.

$line = <STDIN>;
if ($line eq “\n”) {
    print “A blank line was entered.\n” ;
} else {
    print “ That line of input was: $line”;

The “chomp” operator:
-This is an operator that will take the end of line out of a string (only one if multiple exist)
-Every line from a file or STDIN must be ended with  “Enter” key.  That’s the target which “chomp” will remove and return only string.

chomp ($text = <STDIN>); # read text w/o newline char while(<file_handle>) {

“undef” value & the “defined” function:
-Before a scalar variable is given a value, it contains a special value “undef”:
-If the variable is used as a numeric, it acts like zero.
-If the variable is used as a string, it acts like an empty string.
-A variable can be assigned with undef. E.g. $var = undef
-The line-input operator <STDIN> is one operator that can return undef if end-of-file is reached.
-The function “defined” returns false for undef.

$indata = <STDIN>;
if (defined($indata)) {
    print “The input was $indata”;

Lists and Arrays:
-If a scalar(number or string) is the “singular” equivalent, then lists and arrays are the “plural” equivalents.
-Perl allows array variables and scalar variables with the same names exist in the same perl program (kept in separate space).

-A list is an ordered collection of scalars
-A list is the data
-Data in a list is ordered with 1st data numbered zero
-A list value may not be in an array.
-There are no limit on list size
-Lists use parentheses like: ( “a”, “b”, “c”)

-An array is a variable that contains a list
-An array is the variable
-Array index starts with zero
-Every array variable holds a list (the list can be empty)
-There are no limit on array size
-Arrays uses “@” like @myArrayList


$hippo[5] = "me";
$hippo[6] = "you";

print " value in index 5 is $hippo[5]\n";

print "highest index number of array:  $#hippo \n";

 value in index 5 is me
highest index number of array:  6

pop/push and shift/unshift:
-Although perl array can be created and expanded using indexing, however perl provides sufficient facilities to avoid using indexing.
-push/pop adds or removes values from the right side of an array:
a. @ary = (10..20);  $v = pop (@ary); # $v has 20, ary has 10 thru 19.
b. $v2 = pop(@ary); #  $v2 has 19, ary has 10 thru 18.
c. pop @ary ; # ary has 10 thru 17. No assignment is made.
d. push (@ary, 11); # ary has 10 thru 17 and 11.
e. push @ary, 0 ; # ary has 10 thru 17, 11 and 0.

-shift/unshift adds or removes values the left side of an array:
a. $left1 = shift(@ary; # ary has 11 thru 17, 11 and 0.
b. unshift(@ary, 100); # ary has 100, 11 thru 17, 11 and 0.

reverse operator on a list:
-The reverse operator takes a list of values (such as an array) and reverse the order of the values.
@values = (1..23);
@rvalues = reverse (@values); # contains 23 down to 1.

-Reverse does not modify the values it operates on:
@animals = qw/ cat dog cow pig/;
reverse @animals;  # no change to animals array
@r_animals = reverse (@animals);

sort operator on a list:
-The sort operator sorts a list of values according the ASCII value:
@animal = (“cat”, “dog”, “chicken”);
@sorted = sort (@animals); # gets cat, chicken and dog.
@numbers = sort (97..102); # 100, 101, 102, 97, 98 and 99.

-Note that the sort operator does not modify the operand: sort
@animals; # does not modify the array for animals.
@sorted_animals = sort @animals;

-Perl supports the convenient “foreach” construct.
@rock = qw/bedrock lava granite/;

foreach $rock (@rock) {  # both array and scale are allowed by perl in the same context.    print “One rock type is $rock.\n”; }

foreach $i (1..14) {   print “the count is: $i\n”; }

-Perl has a default control variable $_ for foreach:

foreach (1..14) { # this foreach works the same as the last one.   print “the count is: $_\n”; }

<STDIN> in list context:
-Perl extends the reading single line to a list of values using array (use CONTROL-D to finish):
@lines = <STDIN>;

-The chomp command can work on an array:
chomp(@lines); # removes end of line from all lines.
chomp(@lines = <STDIN>); # read lines, leave out newline.

Please click here for Part 2

Post a Comment
Read more: