Comprehensive Guide to Perl Programming for System Administration
This guide covers the fundamentals of Perl programming, including its history, constants, variables, operators, control structures, and file I/O. Learn how to use Perl for effective system administration with practical examples. Understand scalar, array, and associative variables, along with conditional statements and loops. Discover how to implement functions and handle command line arguments. This resource is perfect for beginners and those looking to sharpen their Perl skills for tasks related to system management.
Comprehensive Guide to Perl Programming for System Administration
E N D
Presentation Transcript
PERL By C. Shing ITEC Dept Radford University
Objectives • Understand the history • Understand constants and variables • Understand operators • Understand control structures • Understand functions • Understand file I/O • Understand command line arguments • Understand how to use Perl for system administration
History • Perl (Practical Extraction Report Language) by Larry Wall (1986) • Language between C and shell: Scripting , need interpreter • Provide File access and Unix utilities • Download site: http://www.perl.com • File extension (.pl) • Interpret with error message: • perl -w filename.pl arg0 arg1 … • Artistic license: variation of GNU public license, free
Constants • Scalar: • Number: integer, real, scientific notation • String: within “ “ • Boolean: • 1 represents true • 0 represents false
Variables • Scalar: begin with $ • Number: integer, real • String: string, character • Array: begin with @ • Index starts from 0 • Associative: begin with % • use hash
Control Structures • Print • Assignment • Conditional • Loop • Function (Subroutine)
Control Structures - Print • Syntax: each statement ends with ; Print variable [constant]; • Example: print "Please enter a number:";
Control Structures - Assignment • Syntax: each statement ends with ; Variable = expression Comment: begins with #
Control Structures - Assignment • Scalar Variable • Number: integer, real • Example: $i=5 $j=-6.2 • String: string, character • Example: $month=“January” $char=“\t”
Control Structures - Assignment • Scalar Variable • Number: integer, real • Example: $i=5; $j=-6.2; $number = <STDIN>; (keyboard input) • String: string, character • Example: $month=“January”; $char=“\t”; $guess = <STDIN>; (keyboard input) $fileString = <FILEHANDLE> (getting data from file)
Control Structures - Assignment • Array Variable • Example: @array = ("john", "susan", "david", "sarah", "ryan", "laura"); @numRange = (1..6); Where $array[0] = “john”; $array[1] = “susan”; $array[5] = “laura”;
Control Structures - Assignment • Associative Variable • Example: %hash = ("smith"=>"john", "sides"=> "susan", "davis"=>"david", "star"=>"sarah", "rush"=>"ryan","lane"=> "laura"); Where $array{“smith”} = “john”; $array{“sides”} = “susan”; $array{“lane”} = “laura”;
Operators – Arithmetic, Logic, Relational • Arithmetic: +,-,*,/ • Logical: &&, || • Relational • Numeric: ==, !=, >, >=, <, <= • String: eq, ne, gt, ge, lt, le
Operators - String • String • Concatenation: . • Example: • $month = $month.$char; • $message = "This is a number ".”\t”.$number. "\n"; • Match: =~ • Example; $line =~ s/the/THE/g; (replace all the by THE in the $line) $line =~ /(\w+)(\s+)(\w+)(\s+)/; (line that matches the pattern: word, spaces, word
Control Structures - Conditional • Syntax • If (condition) { } • If (condition) { } else { } • If (condition1) { } elsif (condition2) { } else { }
Control Structures - Conditional • Example: if ($guess eq "hello") { print "The word ".$guess." that you guessed is correct.\n\n"; }
Control Structures - Conditional • Example: if ($avg >=0.895*$avgall) { $grade="A"; } elsif ($avg >=0.795*$avgall) { $grade="B"; } elsif ($avg >=0.695*$avgall) { $grade="C"; } elsif ($avg >=0.595*$avgall) { $grade="D"; } else { $grade="F"; }
Control Structures - Loop • While • Until • Foreach • For
Control Structures – While Loop • Syntax while (condition) { } when condition is false, exit loop
Control Structures – While Loop • while ($line=<USERFILE>) { }
Control Structures – Until Loop • Syntax until (condition) { } when condition is true, exit loop
Control Structures – Until Loop • Example: until ($array2[0] eq "listing") { }
Control Structures – Foreach Loop • Syntax foreach variable (variableRange) { } when variable is outside of variableRange, exit loop
Control Structures – Foreach Loop • Example: foreach $month (1..12) { }
Control Structures – For Loop • Syntax for (initialization; condition; ending body stmt) { } when condition is false, exit loop
Control Structures – For Loop • Example: for ($i=1; $i<=12; ++$i) { }
Control Structures - Function (Subroutine) • Library function • User (-defined) function
Control Structures – Library Function • lc() or lc : convert to lower case • uc(): convert to upper case • open(), close(), die(), exit(), last(): See File I/O • print() • length(): length of string • index()
Control Structures – Library Function • Example: # search item through list foreach $user (@list) { if ($user eq lc($item)) { $user_correct = 1; } } # foreach
Control Structures – Library Function • keys(): gives the key value of the hash • chomp(): delete the new line character from variable • split (delimiter, variable) : split a variable using delimiter • my(): create local variable • shift (arrayName): get rid of 1st element in the arrayName • push (array1, array2): push array2 to the end of array1
Control Structures – Library Function • Example: while ($line=<NAMEFILE>) { chomp($line); # username are separated by space(s) @array=split /\s+/, $line; }
Control Structures – Library Function • Example: foreach $userkey (keys %hash) { if ($hash{$userkey} eq lc($name)) { $user_correct = 1; $lastname=$userkey; } } # foreach
Control Structures – User Function • Function call: • Syntax: functionname (actualParameterList); • Example: check ($name, @array);
Control Structures – User Function • Function definition: • Syntax: sub functionname { my $localVar1 = $_[0]; my $localVar2 = $_[1]; my @localArray = @_; }
Control Structures – User Function • Function definition: • Example: check ($name, @array); sub check { # the following 3 lines declare local variables my $item = $_[0]; my @list = @_; my $user_correct = 0; }
Control Structures – User Function • Example: printArray(@array); sub printArray { # @array is a local variable in the sub my @array = @_; foreach $cell (@array) { print $cell."\t"; } print "\n"; } # sub printArray
File I/O • Open/Close file: • Syntax: open (FILEHANDLE, “<filename”); close (FILEHANDLE);
File I/O • Open/Close file: • Example: # read all names into @array from input data file: sixth2.txt open (NAMEFILE, "<sixth2.txt") || die "Error: Unable to open the file $!"; # open output file for print open (OUTFILE,">attend.txt"); print OUTFILE "Lastname\t\tFirstname\t\tE-Mail Name\n";
Command Line Arguments • perl –w filename.pl arg0 arg1 arg2 … • Arg0, arg1 and arg2… are command line arguments • Inside the program, they are stored in array @ARGV
Command Line Arguments • Example: open (USERFILE, "<user$ARGV[0].txt") || die "Error: Unable to open the file $!"; open (OUTFILE,">attend$ARGV[0].txt"); print OUTFILE "Library Attendance for ITEC 100-$ARGV[0]\n\n";
System Administration • Call system library when using shell commands in Perl • Give full path name for shell commands • Use which command to find full path name • Watch for reserved names in Perl
System Administration • Example: Run Perl in Unix environment • system("/usr/local/gnu/bin/awk '{print \$1,\$2,\$9}' temp1.txt > temp2.txt"); • system("/usr/bin/rm -f temp2.txt"); If you run Perl in Unix, make sure to change data into Unix format, such as: • system("/usr/bin/dos2unix session.txt session.txt");
Reference • Some simple examples