Presentation is loading. Please wait.

Presentation is loading. Please wait.

2.1 Lesson 2: Scalar Functions and Arrays “Perl programming is an empirical science!” - Larry Wall.

Similar presentations


Presentation on theme: "2.1 Lesson 2: Scalar Functions and Arrays “Perl programming is an empirical science!” - Larry Wall."— Presentation transcript:

1 2.1 Lesson 2: Scalar Functions and Arrays “Perl programming is an empirical science!” - Larry Wall

2 2.2 Your very first Perl script print "Hello world!"; A Perl statement must end with a semicolon “ ; ” The print function outputs some information to the terminal screen Now – do it yourself: Write this script in notepad Start  Accessories  Notepad And save (file  save) your script in D:\ex_perl (my computer  D:  perl_ex) With the name hello.pl

3 2.3 Your very first Perl script print "Hello world!"; Traditionally, Perl scripts are run from a command line interface Start it by clicking: Start  Accessories  Command Prompt or: Start  Run…  cmd

4 2.4 Your very first Perl script print "Hello world!"; First let’s go to the correct directory: D: - change drive from C: to D: cd perl_ex - change directory to perl_ex dir - list all the files in the directory (you should see your scirpt here) Running a Perl script perl –w SCRIPT_NAME

5 2.5 Common DOS commands: d: change to other drive (d in this case) md my_dir make a new directory cd my_dir change directory cd.. move one directory up dir list files (dir /p to view it page by page) help list all dos commands help dir get help on a dos command (hopefully) auto-complete go to previous/next command -c Emergency exit More tips about the command line are founds here.here Running Perl at the Command Line

6 2.6 Your very first Perl script print "Hello world!"; Now – change it to your own name… print something additional. And run it again…

7 2.7 Your very first Perl script print "Hello world!"; Compare this to Java's "Hello world": public class HelloWorld { public static void main(String[] args) { System.out.print("Hello World!"); }

8 2.8 Scalar data - revision numeric 3 -20 3.14152965 6.35e-14 ( = 6.35 × 10 -14 )‏ operators: + (addition) - (subtraction) * (multiplication) / (division) ** (exponentiation) ++ (auto-increment) -- (auto-decrement) string double quote: print "hello\tworld"; helloworld single quote (as is): print 'hello\tworld'; hello\tworld operators:. (concatenate) x (replicate)‏

9 2.9 Variables - revision Always use use strict; Variable declaration my $priority; String assignment $priority = 'high'; Numerical assignment $priority = 1; Copy variable my $max = $priority; Change variable $max = $max + 1; $max++;

10 2.10 $a$b 1 1 1 1 2 1 3 0 3 my $a = 1; my $b = $a; $b = $b+1; $b++; $a--; Variables For example:

11 2.11 Scalar Data and functions

12 2.12 Variables - notes and tips Tips: Give meaningful names to variables: e.g. $studentName is better than $n Always use an explicit declaration of the variables using the my function Note: Variable names in Perl are case-sensitive. This means that the following variables are different (i.e. they refer to different values): $varname = 1; $VarName = 2; $VARNAME = 3;

13 2.13 Variables - always use strict! Always include the line: use strict; as the first line of every script. “Strict” mode forces you to declare all variables by my. This will help you avoid very annoying bugs, such as spelling mistakes in the names of variables. my $varname = 1; $varName++; Warning: Global symbol "$varName" requires explicit package name at... line...

14 2.14 Interpolating variables into strings use strict; my $a = 9.5; print "a is $a!\n"; a is 9.5! Reminder: print 'a is $a!\n'; a is $a!\n

15 2.15 Uninitialized variables Uninitialized variable (before assignment) recieves a special value: undef If uninitialized variables are used a warning is issued: my $a; print($a+3); Use of uninitialized value in addition (+) 3 print("a is :$a:"); Use of uninitialized value in concatenation (.) or string a is ::

16 2.16 Reading input <STDIN> allows us to get input from the user: use strict; print "What is your name?\n"; my $name = <STDIN>; print "Hello $name!"; What is your name? Shmulik Hello Shmulik ! $name: "Shmulik\n"

17 2.17 $name: "Shmulik\n" Use the chomp function to remove the “new-line” from the end of the string (if there is any): use strict; print "What is your name?\n"; my $name = <STDIN>; chomp $name; # Remove the new-line print "Hello $name!"; What is your name? Shmulik Hello Shmulik! $name: "Shmulik"$name: Reading input - chomp

18 2.18 The length function The length function returns the length of a string: my $str = "hi you"; print length($str); 6 Actually print is also a function so you could write: print(length($str)); 6

19 2.19 The substr function The substr function extracts a substring out of a string. It receives 3 arguments: substr(EXPR,OFFSET,LENGTH) Note: OFFSET count start from 0. For example: my $str = "university"; my $sub = substr($str, 3, 5); $sub is now "versi", and $str remains unchanged. Also note : You can use variables as the offset and length parameters. The substr function can do a lot more, Google it and you will see…

20 2.20 Documentation of perl functions Anothr good place to start is the list of All basic Perl functions in the Perl documentation site: http://perldoc.perl.org/ Click the link “Functions” on the left (let's try it…)

21 2.21 Class exercise 2.1 1.Write a script that print to the screen the value of 2 in the power of 100 (2 100 ). 2.Write a script that reads a line from the user (using STDIN) and prints the length of it. 3.Write a script that read a line from the user and print the string from the 5 rd letter to the 7 th one. For example for the input: “ The Simpsons ” The script will output: “ Sim ” Reminder: The position of the 1 st letter is 0 (zero).

22 2.22 Lists and Arrays

23 2.23 @arr 3 2 1"fred" @arr * 2 1"fred" 0 1 2 3 Lists and arrays A list is an ordered set of scalar values: (3,2,1,"fred") An array is a variable that holds a list: my @arr = (3,2,1,"fred"); print @arr;321fred You can access an individual array element: print $arr[1];2 $arr[0] = "*"; print @arr;*21fred 3 2 1"fred"

24 2.24 Lists and arrays You can easily get a sub-array: my @arr = (3,2,1,"fred","bob"); print @arr; 321fredbob print $arr[1]; 2 my @sub_arr = @arr[2..3]; print @sub_arr;1fred You can extend an array as much as you like: my @arr2 = ("A","B","C") $arr2[5] = "F"; @arr 3 2 1"fred" "bob" 0 1 2 3 4 @sub_arr 1"fred" 0 1 @arr2 "A""A""B""B" 0 1 2 3 4 5 "F""F" undef "C""C" @arr2 "A""A""B""B" 0 1 2 "C""C"

25 2.25 Lists and arrays Assigning to arrays: my @arr = ('alpha','bravo','charlie','delta'); Multiple assignment: my ($a,$b) = ('cow','dog'); $a='cow'; $b='dog'; my ($a,$b,@c) = (1..5);$a=1; $b=2; @c=(3,4,5) scalar - counting array elements: print scalar(@arr); 4 Last element index: (might issue warning) print $#arr; 3 Last element value: print $arr[-1]; delta

26 2.26 Interpolating arrays You can interpolate arrays and array elements into strings: my @arr = ("a","b","cat",d"); print @arr; abcatd print "@arr"; a b cat d print "$arr[2] is the third element of \@arr"; cat is the third element of @arr

27 2.27 Reading arrays You can read lines from the standard input in list context: my @arr = ; print "@arr"; @arr will store all the lines entered until the user hits ctrl-z. ctrl-z to indicate end of file @arr2 "cogito\n""ergo\n""sum\n"

28 2.28 Reading arrays chomp will work on each entry of the array my @arr = ; chomp @arr; print "@arr"; @arr2 "cogito\n""ergo\n""sum\n" @arr2 "cogito""ergo""sum"

29 2.29 Manipulating arrays – push & pop my @arr = ('a','b','c','d','e'); print @arr;abcde push(@arr,'f'); print @arr;abcdef ----------------------- my @arr = ('a','b','c','d','e'); my $num = pop(@arr); print $num;e print @arr;abcd e f a b c d 0 1 2 3 4 5 @arr $num

30 2.30 shift & unshift my @arr = ('a','b','c'); my $num = shift(@arr); print $num;a print @arr;bc --------------------- my @arr = ('a','b','c'); print @arr;abc unshift(@arr,'?'); print @arr;?abc 0 1234

31 2.31 split & join my @arr; my @arr2; @arr = split(/ /, "You talkin to me? You talkin to me?"); @arr = ("You","talkin","to","me?","You","talkin","to","me?") @arr2 = split(//, "You talkin to me? You talkin to me?"); @arr2 = ("Y","o","u"," ","t","a","l","k","i","n"," ",...) my $str = join("-", @arr); print "$str\n"; "You-talkin-to-me?-You-talkin-to-me?"

32 2.32 Reversing lists my @arr = ("yossi","bracha","moshe"); my @rev_arr = reverse(@arr); print join(";", @rev_arr); moshe;bracha;yossi

33 2.33 Sorting lists Default sorting is alphabetical: my @arr = sort("yossi","bracha","moshe"); # @arr is ("bracha","moshe","yossi") my @arr2 = sort(1,3,9,81,243); # @arr2 is (1,243,3,81,9) Other forms of sorting require subroutine definition: my @arr3 = sort(compare_sub 1,3,9,81,243); We might get to that latter… Note: sort and reverse do not change the array. They return a new array after the operation of the function (that should be saved in another array if needed for further use).

34 2.34 Class exercise 2.2 1.Read a number from the first line of input, and then read the rest of the lines into an array (stop by using ctrl-z). Print the line selected by the number provided in the first line. 2.Read a list of numbers separated by spaces, and print those numbers in reverse order, separated by slashes (/). 3.Read a list of words separated by spaces, sort and print them. 4.Like in 3, but return only the last word (after the sorting). 5.Like in 3, but reverse the order of the letters of the last word

35 2.35 Comments on exercise 1 Always run your script with “ perl -w ” and take care of all warnings  submitted scripts should not produce any warnings The file should end with.pl extension. Write a separate file for each question, and name the scripts: “ ex2.1.pl ”, “ ex2.2.pl ”, “ ex2.3.pl ”… When submitting exercises by email write your name and the exercise number in the subject line (for example “ Shmulik Israeli perl ex. 2 ”) You can use the computer classroom if you wish.

36 2.36 Comments on exercises Use meaningful names for variables. We always add " use strict; " in the first line of scripts (once is enogh). Always declare variables using " my $newVarName; ". Use chomp function to omit newline ( "\n" ) from input.

37 2.37 Comments on exercises Mind the input (parameters given by user) and the arguments (parameters used by functions): The input of Question 4 is somewhat tricky… The parameters of substr are: 1) string 2) start 3) LENGTH and in the exercise the request was that the numbers will be 1) start 2) stop 3) duplications

38 2.38 Adding comments Comments: The # symbol, and anything from it to the end of the line is ignored. # read two values from the user my $num1 = my $num2 = # calculate their sum my $sun = $num1 + $num2;

39 2.39 Adding comments Comments: If you want to insert a comment of multiple lines, you can use =begin and =cut. =begin This program prints stuff. Here you can write any text you want and you don’t need any # =cut print "stuff\n";


Download ppt "2.1 Lesson 2: Scalar Functions and Arrays “Perl programming is an empirical science!” - Larry Wall."

Similar presentations


Ads by Google