Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linux Operating System

Similar presentations


Presentation on theme: "Linux Operating System"— Presentation transcript:

1 Linux Operating System
Unit 6: More Scripting in Linux 4/22/2017 Linux Operating System A Practical Guide to Fedora and Red Hat Enterprise Linux Unit 6: More Scripting in Linux Chapter 28: The Perl Scripting Language By Fred R. McClurg © Copyright 2013, All Rights Reserved Chapter 28: The Perl Scripting Language

2 Perl History Written in 1987 by Larry Wall
Backronym: Practical Extraction and Report Language Influenced By: C Language Bourne Shell AWK sed

3 Perl Strengths Purpose: Strengths: System Administration
Bioinformatics Text Processing General Purpose Strengths: Portable Informal Practical Robust Easy-to-use Complete

4 Perl Distinctions Nicknamed: The Swiss Army chainsaw of programming languages Motto: TIMTOWDI (pronounced “Tim Toady”) acronym for “There is more than one way to do it” Slogan: Easy things should be easy and hard things should be possible

5 More Perl Distinctions
Interpreted: Code does not need run through a compiler (compiled at run-time). Dynamically Typed: Variable types do not have to be declared. Type is determined at run-time by the context. Side effects are often beneficial!

6 Executing Perl First line of file: #!/usr/bin/perl
Via shell command (Win & Linux): perl script.pl After chmod +x (Linux only): script.pl

7 Perl Documentation Online: perldoc: Man page-like docs Books:
Programming Perl (Camel book) Learning Perl (Llama book) Online:

8 Perl Terminology Variable: Block: Named storage for values.
Zero or more statements surrounded by curly braces “{}”.

9 Perl Terminology Function: Module:
Self Contained set of instructions that can be called repeatedly. Module: Encapsulated collection of functions, similar to a library in other languages.

10 More Perl Terminology Statement: Single instruction or command
Every statement must end with a semi-colon “;” White space in a statement does not matter except within a quoted string.

11 Variable Types: Perl Variables Scalar Variables: “$”
Array Variables: Hash Variables: “%”

12 Scalar Variable Defined
Defined: A named memory location containing a single value. Begins with “$”

13 Storing Scalar Variables
Examples: $bugs = "Wabbit"; $fudd = "Wascal $bugs"; $money = '$1,000,000'; $count = 70; $times = "7"; $PI = ; $forgive = $count * $times;

14 Displaying Scalar Variables
Examples: print $bugs . "\n"; print "$fudd\n"; printf( "%s\n", $money ); printf( "%d\n", $times ); printf( "%02.3f\n", $PI ); printf( "%s\n", $forgive ); printf( "%d\n", $forgive );

15 Scalar Variable Output
Script Output: Wabbit Wascal Wabbit $1,000,000 70 3.142 490

16 Array Variable Defined
Defined: A collection of variables referenced by a numeric index. Often called a list. Begins with

17 Array Initialization by Element
Example: $marx[0] = "Groucho"; $marx[1] = "Harpo"; $marx[2] = "Chico";

18 Array Initialization via List
Example: @marx = ( "Groucho", "Harpo", "Chico" );

19 Defined: A collection of variables referenced by a numeric index
Hash Variable Defined Defined: A collection of variables referenced by a numeric index Begins with “%”

20 Hash Initialization by Element
Example: $comic{'hulk'} = "David Banner"; $comic{'superman'} = "Clark Kent"; $comic{'batman'} = "Bruce Wayne";

21 Hash Initialization One Step
Example: %comic = ( "hulk" => "David Banner", "superman" => "Clark Kent", "batman" => "Bruce Wayne" );

22 if : Flow Diagram if statements True False

23 if: Control Structure Definition: Evaluates the logical condition: if expression is true, statements are executed Syntax: if ( condition ) { statements; }

24 if : Command Arg Example
Purpose: Display first 3 command line arguments if specified if ( $#ARGV == 2 ) { print "$ARGV[0]\n"; print "$ARGV[1]\n"; print "$ARGV[2]\n"; }

25 if: Command Prompt Example
Purpose: Guess the “mystery” word when prompted $target = "secret"; print "Guess word: "; $guess = <>; chomp( $guess ); if ( $guess eq $target ) { printf( "That's right!\n“ ); }

26 if: Expression Modifier
Definition: Evaluates a logical condition and controls whether or not statements are executed Syntax: statement if ( cond );

27 if : Modifier Example Purpose: Display message if three arguments specified print "Three args\n" if ( $#ARGV == 2 );

28 unless : Flow Diagram unless statements False True

29 unless: Control Structure
Definition: Evaluates the logical condition: if expression is false, statements are executed Syntax: unless( condition ) { statements; }

30 unless : Example Purpose: Prompt user for age and display a cheerful word of encouragement. $retirement = 65; print( "Enter age: " ); $age = <>; unless ( $age >= $retirement ) { print( "Get to work!\n" ); }

31 if ... else: Structure Definition: Evaluates a condition. If condition is true, control follows one branch. If the condition is not true (else), control follows a different branch. Syntax: if ( condition ) { statements; } else

32 if ... then ... else: Flow Diagram
statements else branch True False

33 if ... else: What is truth? if ( 0 ) { print( "Right!\n" ); } else
Purpose: Determine what is true and what is false. Question: What is printed here? if ( 0 ) { print( "Right!\n" ); } else print( "Wrong.\n" );

34 if ... else: Guess a number Purpose: Guess a “mystery” prompted number
$target = 4; print( "Guess number: " ); $guess = <>; if ( $guess == $target ) { print( "Right!\n" ); } else { print( "Wrong.\n" );

35 if ... elsif ... else: Flow Diagram
False if statements True False if branch elsif statements True else elsif branch else fallback statements

36 if ... elsif ... else: Example Purpose: File type of command-line argument $file = $ARGV[0]; if ( -l $file ) { printf( "Link: %s\n", $file ); } elsif ( -f $file ) { printf( "File: %s\n", $file ); elsif ( -d $file ) { printf( "Directory: %s\n", $file ); else { print( "Not link, file, or directory\n" );

37 Comparison Operators == eq Equals != ne Not equals < lt Less than
Numeric String Description == eq Equals != ne Not equals < lt Less than > gt Greater than <= ge Greater or equal to >= le Less or equal to

38 foreach: Flow Diagram False foreach true foreach True statements

39 foreach: Looping Structures
Description: Structure that performs given number of iterations on a statement or statements Syntax: foreach $var ) { statements; }

40 foreach: Looping Example
Purpose: Display all elements in an array @dwarfs = ( "Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey" ); foreach $dwarf ) { print( "Dwarf: $dwarf\n" ); }

41 for: Looping Structure
Description: General purpose looping structure for a given iteration Syntax: for ( init; cond; incDec ) { statements; }

42 for: Looping Example Purpose: Count down from 5 to 1
for ( $i = 5; $i > 0; $i-- ) { printf( "Count: %d\n", $i ); } print( "Lift off!\n" );

43 while: Flow Diagram False while true while True statements

44 while: Looping Structures
Description: Structure that performs iterations while a condition is true (i.e. repeat until false) Syntax: while ( condition ) { statements; }

45 while: Looping Example
Purpose: Count file lines (wc -l) while ( $line = <> ) { $count++; } print( "Lines: $count\n" );

46 until: Flow Diagram True until until false False commands

47 until: Looping Structures
Description: Structure that performs iterations while a condition is false (i.e. repeat until true) Syntax: until ( condition ) { statements; }

48 until: Looping Example
Purpose: Guess a number $secret = 4; print "Number between 1 & 10\n"; print "Your guess: "; until ( $secret == ( $guess = <> ) ) { } print( "Correct!\n" );

49 last: Looping Interrupt
Description: Terminates the current iteration and breaks out of the loop Example: for ( $i = 1; $i < 6; $i++ ) { last if ( $i == 3 ); print( "$i\n" ); }

50 next: Looping Interrupt
Description: Terminates the current loop and continues the next iteration Example: for ( $i = 1; $i < 6; $i++ ) { next if ( $i == 3 ); print( "$i\n" ); }

51 sort: Function Description: Returns a sorted list @reindeers =
( "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen", "Rudolph" ); @reindeers = ); foreach $reindeer ) { print "$reindeer\n"; }

52 subroutine: Custom Function
Description: Encapsulates a set of commands $first = 1; $second = 2; &add(); print "Answer: $ansr\n"; sub add() { $ansr = $first + $second; }

53 Returning subroutine value
Description: Returning a value from sub $first = 1; $second = 2; $ansr = &add(); print "Answer: $ansr\n"; sub add() { return( $first + $second ); }

54 Passing subroutine params
Description: Passing parameters to a subroutine $first = 1; $second = 2; $ansr = &add( $first, $second ); print "Answer: $ansr\n"; sub add() { my( $one, $two ) return( $one + $two ); }

55 Regular Expression matching
Description: Few character wildcards can perform powerful pattern matching. print( "Enter a number: " ); chomp( $digit = <> ); if ( $digit =~ /^[0-9]+$/ ) { print( "Thanks!\n" ); } else { print( "Not a number\n" );

56 Regular Expressions Char Matches ^ Beginning of line anchor $
End of line anchor (...) Regular expression grouping . Any character except newline “\n” \\ Backslash (escaped) * Zero or more of previous ? Zero or one of previous + One of more of previous

57 More Regular Expressions
Char Matches [...] Set of characters \d Numeric digit [0-9] \D Non-numeric digit [^0-9] \s White space (space, tab, newline, etc) \S Non-white space [^\s] \w Word char (alpha or numeric) [a-zA-Z0-9] \W Non-word character [^a-zA-Z0-9]

58 Greedy & Non-greedy Matches
Description: Regular expressions usually match the longest string possible (greedy matches). Non-greedy regular expressions match the shortest string possible.

59 REs are usually greedy Example:
$html = "<b>bold font</b>"; $text = $html; $text =~ s/<.*>//g; print "Text: \"$text\"\n";

60 Making a RE non-greedy Example:
$html = "<b>bold font</b>"; $text = $html; $text =~ s/<.*?>//; print "Text: \"$text\"\n";

61 Grouping Patterns Example: $firstLast = "Fred McClurg";
$lastFirst = $firstLast; $lastFirst =~ s/([^\s]+)\s([^\s]+)/$2, $1/g; print "$lastFirst\n";

62 split and other stuff @passwd = `cat /etc/passwd`; foreach $line ) { chomp( $line = split( /:/, $line ); # frmcclurg:x:500:500:Fred R. McClurg:/home/frmcclurg:/bin/bash $shell = $parts[6]; $userCount++; $shells{$shell}++; } printf( "User count: %d\n\n", $userCount ); foreach $shell ( keys %shells ) { printf( "Shell: %s\t%d\n", $shell, $shells{$shell} );

63 Debugging Shell Scripts
Description: Print warning messages regarding possible problems Example: #!/usr/bin/perl -w

64 Debugging Shell Scripts
Description: Force declaration of variables. Example: use strict; my( $variable ) = 0; print "$variable\n";


Download ppt "Linux Operating System"

Similar presentations


Ads by Google