An Introduction to Perl – Part I Emily Goldberg Perl, a compact Unix-type scripting language created in the 1980’s, is an easy to write language with multiple uses. The primary uses of Perl are administrative tasks and server-side scripting for web pages.
Scalar Data Scalar – holds one piece of data Numbers: Floating-Point Integer Non-decimal 3.11023 -12 0377 octal -2.7e32 3_814_524_705 0xff hex 0b11111111 binary The basic unit of data is scalar data. Scalars can be numbers or strings. If a box is a container that holds one pair of shoes, then a crate is a container that holds multiple boxes. Similarly, scalar data (i.e.- strings, integers) hold one piece of data as opposed to a list which is a collection of scalars.
Scalar Data (cont’d.) Strings: Single-Quoted Double-Quoted 'hello\nthere' hello\nthere “hello\nthere” hello there $string="world"; print "hi $string \n!"; hi world !
Variables Use $ prefix to denote a variable Ex.- $_points=5; $name2=‘Larry’; Variable names can contain letters, numbers, and underscores, but may NOT begin with a number.
Operators Number Operators Operation Operator Example Add + Subtract - Multiply * Divide / Modulus % 10.5%3.2 = 1 Exponentiation ** 2**3 = 8 Assign =, *=. += Comparison ==, !=, <,>,<=,>=
Operators (cont’d.) String Operators Operation Operator Example Concatenation . "hello"."world" helloworld Repetition x “hello”x3 hellohellohello Comparison eq, ne, lt, gt, le, ge Assignment =, *=. +=, .= $name2.=‘ Lee’ larry Lee
Automatic Conversion Operations Results "hello“ . 3 * 5 “hello15" “12” * “3” 36 "12fred34" * " 3" 12 - ”fred” 12
Standard Input/Output Ex. - print "The answer is ", 6 * 7, ".\n"; Input Ex. - $line=<STDIN>; Remove “\n”- chomp($line);
Control Structures: if-else if ($language eq “Perl”) { print “Always use curly braces!” ;} else { print “ Who knows?!”;}
Control Structures: while while(defined($line=<STDIN>)) {chomp($line); print “This line was: $line \n”; } while(<>) { chomp; print “This line was: $_ \n”; }
Lists and Arrays A list is an ordered collection of scalars. An array is a variable that contains a list. A list with five elements
Lists and Arrays(cont’d.) @numbers=(1,2,3,4); @numbers=(1..4); numbers[0]=‘one’; print $numbers[$#numbers]; $a=pop( @numbers); push( @numbers, $a+3);
Questions?
Refrences Learning Perl by Randal Schwartz and Tom Phoenix (Via Drexel Library electronic resources) “Perl Basics” (http://www.cs.drexel.edu/~knowak/cs265_fall_2009/perl_basics.pdf)