Presentation is loading. Please wait.

Presentation is loading. Please wait.

Perl Subroutines User Input Perl on linux Forks and Pipes.

Similar presentations


Presentation on theme: "Perl Subroutines User Input Perl on linux Forks and Pipes."— Presentation transcript:

1 Perl Subroutines User Input Perl on linux Forks and Pipes

2 Subroutines

3 Subroutines are named code blocks Used to: – shorten code blocks in larger programs –Avoid repeating code blocks re-useable code –Implement “abstraction” your own “high level” language Sometimes called “user defined functions”

4 Subroutines Shorten code blocks in larger programs Miller Number (7 +or- 2) – http://www.musanim.com/miller1956/ http://www.musanim.com/miller1956/ People seem to be able to hold that many things in memory –Registers? So we want to break modules down into that many pieces

5 Subroutines On the decomposition of programs into modules – http://sunnyday.mit.edu/16.355/parnas-criteria.html http://sunnyday.mit.edu/16.355/parnas-criteria.html Encapsulate design decisions Minimise connections between modules Disciplined data flow –No global variables

6 Subroutines Subroutines are declared –sub mysub {block} Not run until "called" Subroutines are functions –they return a value Actually a list –return value is value of last expression evaluated –or values referenced in "return" statement

7 Subroutines Subroutines can be run by referencing their name like a function –mysub(); –mysub; –&mysub; & before the subroutine name may be required if the reference to the subroutine precedes its definition in the source file If you like to define subs after referencing them, precede the reference with &

8 Getting data in and out Variables in perl are global by default But you want to pass data to a subroutine as a parameter – not as a global variable Subroutines receive parameters just like main program – in an array Programs get command line parameters in @ARGV array Subroutines get values in @_ array

9 Example sub adder { return $_[0] + $_[1]; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result: cmblap:~ # perl test.pl 3 13 cmblap:~ #

10 Private Variables Example sub adder { $sum= $_[0] + $_[1]; return $sum; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result cmblap:~ # perl test.pl 3

11 Private Variables sub adder { my $sum; $sum= $_[0] + $_[1]; return $sum; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result cmblap:~ # perl test.pl 3 13

12 Data Flow Always pass data to subroutines as parameters Always return information as a return value, or modified parameters –Return value is better Make reference only to variables declared private (using “my $variable_name” etc) in the subroutine

13 User Input

14 $inputline = ; This tells Perl to read a line of text from standard input (represented by STDIN) and assign this value to the variable $inputline. A line of text is s text string terminated by a line terminator Standard input is the keyboard by default

15 User Input Sample program input.pl $input= ; print "Here is what I typed: $input"; Sample output: cmblap:~ # perl input.pl some stuff Here is what I typed: some stuff cmblap:~ #

16 User Input A slight change: $input= ; print "Here: $input is what I typed "; New Output: cmblap:~ # perl input.pl some stuff Here: some stuff is what I typed cmblap:~ #

17 User Input Another slight change: $input= ; chomp $input; print "Here: $input is what I typed: \n"; Output cmblap:~ # perl input.pl more stuff Here: more stuff is what I typed: cmblap:~ #

18 chomp The chomp function removes a trailing newline from a variable. chop is similar but removes the last character no matter what it is. chomp is used to clean up input

19 Perl on Linux

20 Perl on linux May be many more packages Especially if the windows perl uses PPM –ActivePerl Sometimes newer versions Command line switches slightly different Shabang line different

21 Running perl Open a command line window –Sometimes called terminal window in linux cmblap:~ # perl -e 'print "Hello World\n" ' Hello World cmblap:~ #

22 Editing Perl scripts Kali linux doesn't come with a good editor for perl but gedit can be installed with apt- get install gedit then gedit test.pl Syntax highlighting makes it a little easier to know if you have committed errors

23 shabang At command prompt type whereis perl –to find out path to perl enterpreter Should say /usr/bin/perl Put shabang line: #!/usr/bin/perl -w at the start of your program

24 Make your program executable In linux files to be executed need to have executable permission chmod +x myfile.pl makes myfile.pl executable Then you can run it like this:./myfile.pl –“./” means current directory Or you can just type perl myfile.pl

25 Saving Your Program No “H” drive in linux –To access your “H” drive use the web interface Program output can be saved to a file using redirection./myprogram.pl > some-file.txt Runs myprogram.pl and saves the output in some-file.txt Flash drive will be a subdirectory of /media

26 Saving Command Line History Highlight the text you want to save Move to editor Middle button pastes highlighted text into the editor

27 Forking child processes

28 Forks Forking creates a new sub-process with the process that did the forking as the parent process In perl, the sub-process is identical to the parent and begins execution at the same point File descriptors are shared, and the child gets a copy of everything else

29 The fork Function fork Takes no parameters Returns –To the parent: The pid (process id) of the child Or Undef if the fork failed –To the child Zero

30 Waiting on your children The wait function waits for a child process to die Returns the pid of the child Or -1 if there are no children If a forking process doesn't wait for the children to die they may become zombies

31 Example if ($pid = fork) { &parent ($pid); # pass child pid to # parent subroutine waitpid($pid,0); # wait till child dies } elsif (defined $pid) { &child; # do child subroutine } else { die "cannot fork: $!"; }

32 pid Parent receives pid of child as return value of fork function waitpid $pid can be used to wait for a particular child's death (in case you have many) Built-in variable $$ contains your own pid

33 Talking to your children Pipes

34 pipe function The pipe function creates a pipe and two file handles Example: pipe(READER, WRITER); The first file handle can be used to read data from the pipe The second can be used to write to the pipe Create the pipe before forking so parent and child can share the pipe

35 Unidirectional / Bidirectional pipes are bidirectional, so processes could both read and write to the same pipe This can lead to problems: –Reads are blocking, so if both processes read the pipe at once, both will block and nothing will ever happen –Read will return with UNDEF (like end of file) when all writers are closed, but reader must close its own write file handle first or this will never happen Easier to be unidirectional by closing the unused file handle

36 Writing to the pipe print WRITER "$msg\n"; A problem: pipe IO is block buffered Reader may not see the message for a while –Maybe not until the writer closes the pipe –Fix this by turning on autoflush autoflush WRITER 1; or select WRITER; #WRITER now default FH $| = 1; select STDOUT;

37 Reading from a pipe while (my $line = ) { print "pid $$ received: $line"; } Just like reading a file Blocking read Reads to next line terminator $line will be UNDEF when writer closes the pipe, or terminates

38 Today's lab Create a pipe Fork a sub-process Parent gets a message from the user, sends it to the child Child gets the message, prints it to the screen Repeat until user doesn't enter a message Simple, (really)


Download ppt "Perl Subroutines User Input Perl on linux Forks and Pipes."

Similar presentations


Ads by Google