Karan Thaker CS 265 Section 001 Introduction to Perl Karan Thaker CS 265 Section 001
Topics Covered What is Perl? Scalar Data Variables and Operators If-else and while control structures Standard input Lists and Arrays
What is Perl? Practical Extraction and Reporting Language Very widely used SCRIPTING language Designed for text processing “There’s more than one way to do it”
Scalar Data Simplest type of data that PERL manipulates Either a number or string Can be acted upon with operators (like plus or concatenate) Integers and floats have essentially the same format “undef” – special value assigned to all variables Zero when assigned to numbers NULL when applied to strings
Variables and Operators Naming: Begins with “$” followed by the identifier For example, $karan, $drexel, $computer Any scalar variable holds a SINGLE scalar value Operators Assignment = Arithmetic + , - , * , / String -string concatenation (a dot), x –string repetition Numeric comparison == , != , < , > , <= , >= String comparison eq, ne, lt, gt, le, ge
Control Structures if - else while Similar to C++ Curly braces required if - else while if(...) { ... }else ( } if(...) { ... } while(...) { ... }
Standard Input $line =<STDIN>; Reads a full line from input and stores it in variable $line $line=<STDIN>; if($line eq "\n"){ print "This was an empty line.\n"; } else { print "This line was not empty.\n"; } A line of input is read and one of the two strings is printed out while(defined($line=<STDIN>)){ print “This line was: $line \n”; } Input is displayed in output, and loop stops when end-of-file is reached.
Lists and Arrays Reading into a list Accessing list elements (1,2,3,4,5,6,7,8,9,10) # list consisting of numbers 1 to 10 (1..10) # same list created by the range # operator ($a ..$b) # the range determined by current values of $a and $b Reading into a list Accessing list elements @numbers=(1..100); print $numbers[0]; # prints 1 print $numbers[10]; # prints 11 while(<>){ $lines[$index]=$_ ; $index=$index+1; } print $#lines+1; print @lines; List Assignment ($fred, $barney)=($barney, $fred); # values are swapped @numbers=(1..10); # list (1..10) is stored inside an array
Thank you