Perl Introduction
Perl Introduction
PDT-009679
Course: Introduction to Perl Code: PDT-009679 Content Owner: Matt Jones (matthew.s.jones@intel.com) Last Update: 30 December 2009 Web site: http://perl.intel.com Contributors: Kamlesh Kumar (kamlesh.kumar@intel.com) Ken Stephens (kenneth.g.stephens@intel.com) Ingo Schmiegel (ingo.schmiegel@intel.com) Steve Willoughby (steve.willoughby@intel.com) Michael Ewan (michael.ewan@intel.com) Phil Brothers (phil.brothers@intel.com) All of the Perl instructors at Intel Costa Rica!
1. Introduction
What to expect in this course Perls strengths and weaknesses Typographical conventions used
Introduction to Perl
PDT-009679
Agenda
Part I
1. Introduction - Lab 1 2. Data Handling Break Lab 2a Lab 2b
The basics of Perl, which is a lot, so youll be able to code right away Plan on participating in discussions and ask questions when they come to you Give the labs an honest effort because the only way to learn Perl is to use it
Agenda
Part III
7. Reg. Expressions Lab 7a / break RE functions Lab 7b
Created by Larry Wall in 1987 while working as a programmer at Unisys Is a "backronym" for Practical Extraction and Report Language Is interpreted, rather than compiled Perl 5 was released in 1997 and it is still being maintained
Lab 1: Introduction
Write a Perl script that will print your name and the product of your two favorite numbers Make it similar to the simple Perl script on the previous slide If you have any questions, ask them!
Strings
A string is a sequence of zero or more characters A literal string may be defined by enclosing it in quotes A string variable holds a single value and its name is always preceded by a dollar sign ($) $string = "Hello world!";
2. Data Handling
Scalar data types Variable names Variable scope Operators Lists and arrays Data manipulations
PDT-009679 September 2009 Slide 17
Numbers
A number is a single numeric value Examples of numeric values:
240 22.4 6.02e23 0xff3c 0577 1_395_423 # # # # # # integer floating point sci. notation hexadecimal octal _ is OK
Variable names
A scalar variable starts with a $ and is followed by a letter or an underscore, then any number of alphanumerics Valid names $first_score $Strvar2 $_sorted Invalid names $2bit varname $var.name
Undef
Perl has a special scalar value: undef This is both a function, undef(), and a value used in advanced data structures The undef command can be used to unassign a variable (delete from memory) Undef has no value, it is undefined
Special variables
We will cover several special variables in this class, they are: $_ the default variable (incl. @_) $1-9 placeholder variables $$ the process ID $| the autoflush variable @ARGV the command line arguments
PDT-009679 September 2009 Slide 25
Undef
Use undef() to undefine a variable Use defined() to determine whether a variable is defined Examples:
undef($var); if ($var) {} if (! (defined($var))) {} # false # true
Environment variables
Environment variables may be accessed from a Perl script using $ENV{env}, where env is the environment variable name They can be used directly, created, or assigned to other variables; this is better than hard-coding into your script If the environment variables change while the script is running, the changes won't be noticed by the script
Variable scope
Variables do not have to be declared, but doing so is considered good practice Variables are global by default, but those should be use sparingly to avoid problems A variables scope can be restricted using the "my" function within a block of code
Example: my $string = "hello";
Numeric operators
Strings may be auto-incremented, too!
$var = "a9"; $var++; # $var is now b0 $var = "aa"; $var++; # $var is now ab $var = "zz"; $var++; # $var is now aaa
PDT-009679 September 2009 Slide 30
Operators
Perl has lots of operators for use with strings and numbers Operator precedence and associatively are important, so be careful You can use the UNIX command "perldoc perlop" to view information about Perl operators
PDT-009679 September 2009 Slide 28
Numeric operators
Assignment operators perform an operation on a variable and assign it to the same variable name
=, +=, -=, *=, /=
Examples:
$x = 3; $x += 5; # $x is now 8 $x = 3; $x *= 5; # $x is now 15
Numeric operators
Arithmetic operators
+, -, *, /, %, **, <<, >>
String operators
Two strings can be concatenated using the . (period) operator
$x = "one"; $y = " two"; $z = $x.$y; # $z is "one two"
This is more commonly done using the string interpolation behavior of double quote marks:
$x = "one"; $y = " two"; $z = "$x$y"; # $z is "one two"
This can also be done using the string concatenation assignment operator (.=)
$z = "one"; $z .= " two" # $z is "one two"
Operators
Warning: Performing numeric operations on strings and string operations on numbers can have some unexpected results, so make sure you know what you're doing!!
$x = "one"; $y = " two"; $z = $x + $y; # $z is 0
String functions
$line = "WWID = 10010010"; $wwid = substr($line, -8, 8); # $wwid is 10010010 This is a useful (and faster) way to grab the last number of characters from a string without using regular expressions (which we'll cover later)
String functions
lc(), uc() change case of an entire string to lower case or upper case lcfirst(), ucfirst() change case of the first letter of a string to lower or upper case substr(), length() extract a substring from or find the length of a string chomp(), chop() remove the new line or the last character from a string
PDT-009679 September 2009 Slide 34
String functions
$len = length($name); # $len is 17 $str = "plants\n"; # \n is newline chomp($str); # removes newline # $str is "plants" (no newline) chop($str); # removes last char. # $str is "plant" (no newline)
String functions
$str = "fred"; $ustr = uc($str); # $ustr is FRED $ufstr = ucfirst(lc($str)); # $ufstr is Fred $name = "first last"; substr($name, 6, 0) = "middle "; # $name is first middle last
Boolean operators
Numeric logical operations
<, >, <=, >=, ==, != Note: If $x = "0" and $y = "0.0" then $x == $y is true, but $x eq $y is false.
Scalars: Review
String, numeric, boolean, and undef Scope is global by default (use my) Scalars are single elements Variable names begin with $ Be sure and use the right operator based on the context of the evaluation
PDT-009679 September 2009 Slide 39
Range operator
The range operator is represented by a double dot (..) and is used to generate a list of numbers or letters. It can be used as constant initialization for a list, or can be used in a loop.
@list = (1..100); foreach $var (a..z) {}
15-minute Break
Using arrays
@ra = (3,4,5,6,7); @ra = (3..7); @b = @ra; $el = $ra[2]; ($a, $b) = @ra; # a list of integers # using range operator # copy @ra to @b # assigns 5 to $el # assigns 1st 2 elements
($a, $b, @c) = @ra; # assigns all elements print @ra; print "@ra"; # prints 34567 # prints 3 4 5 6 7
Splitting a string
The "split" function breaks a string into part on the basis of a specified delimiter returning a list of string fragments between each delimiter Syntax: split (delimiter, string [, maxItems]); Note: the delimiter may be a simple string or regular expression; the default maxItems value is unlimited
Splitting a string
Examples: $s = "1:2:3"; @a = split(":",$s); # assign $s # @a = 1 2 3
$s = "list file1 file2"; # re-assigns $s ($key, $rest) = split(/\s+/, $s, 2); # $key = "list"; # $rest = "file1 file2"; Note: /\s+/ is a regular expression (RE) that means "one or more white spaces"
Joining a list
The "join" function attaches the elements of a list into a string with fields separated by a delimiter Syntax: join (delimiter, list); Examples: @a = ("1","2","3"); $s = join(", ",@a); # assign @a # $s = "1, 2, 3"
Splicing a list
The "splice" function for lists is similar to the "substr" function for strings Syntax: splice (a1, offset, length, a2); Notes: a2 is inserted into a1 starting at offset and overwriting length items If splice is assigned to a list, what is overwritten will be stored in the new list
Note: using an alpha sort would result in @a2 = 12 2 3, which is not as expected; use {$b <=> $a} for a descending sort
Splicing a list
Examples: @a1 = ("a","b","c"); # assign @a1 @a2 = ("d","e","f"); # assign @a2 @a3 = splice (@a1, 1, 1, @a2); # a1 gets (a, d, e, f, c) # a3 gets (b)
Arrays: Review
Arrays are defined using @array Individual elements are accessed using $array[index], where index starts at zero and ends at $#array Use the proper type of sort depending on the data being sorted
Using hashes
Example: %hash = ("john" => "32", "bill" => 45, "joe", "25", "fred", 24); $hash{"harry"} = 42; # adds "harry" => 42 to the table $age = $hash{"john"}; # age is 32
10
Hashes: Review
Hash table syntax is %hash Hash element syntax is $hash{key} Hash functions: keys(), values(), each(), delete(), defined(), exists() Can use sort on hash keys
Agenda
Part III
7. Reg. Expressions Lab 7a / break RE functions Lab 7b
Part IV
8. Input & Output - Lab 8 / break 9. Subroutines - Lab 9 10. Wrap-up
3. Quoting Text
Using simple text strings Interpolating string text Using special characters Using escape codes Using "q" functions
Agenda
Part I
1. Introduction - Lab 1 2. Data Handling Break Lab 2a Lab 2b
String (text) literal values are enclosed in quotation marks: 'Hello, world!' Every character between the quotes is kept literally as typed (except \\ & \') $str = 'The value of x is $x\n'; print "$str\n"; > The value of x is $x\n
PDT-009679 September 2009 Slide 71
11
Special characters
Backslash (\) introduces a special character sequence which would be difficult to type directly The string constructed will contain the special characters represented by code
Variable names beginning with $ (scalar) or @ (list), but not % (hash) Array element subscript expressions Literal math expressions (i.e., 4 * 3 will not be changed to 12) Special character "escape codes"
12
"q" functions
Single quoting: $str = q/Hello/; Double quoting: $str = qq/$name/; Execution string: $pwd = qx/pwd/; Quote words: @list = qw/one two/; Can use almost anything instead of / $str = q#Hello#;
PDT-009679 September 2009 Slide 78
4. Advanced Printing
print statement defaults Formatted print function Controlling the print field String format print function
http://perl.intel.com/intro/labs/lab3.pl
13
Name: 1234567
PDT-009679 September 2009 Slide 89
Left justifying
Syntax: %[-[width]]field_specifier
printf ("Name: %-7s %d\n", "Joe", 10); printf ("Name: %-7s %d\n", "Bob", 7); printf ("Name: %-7s %d\n", "Steve", 12); printf ("Name: %-7s\n", "1234567");
14
My WWID is: 10074409 My WWID is: 000000010074409 WWID 10074409 Matthew S. Jones
15
15-minute Break
Control structures: if
Examples: if ($x > 10) { } if ($flag) { } else { } if ($x > 10) { } elsif ($x > 5) { } else { }
5. Flow Control
If / unless While / until For / foreach Reversing some functions Next / last / goto / redo
Control structures: if
if (expr) { } elsif (expr2) { } else { } If expr is true then the first { } block will be executed; if not and expr2 is true then the second { } block will be executed; if not then the third { } block will be executed The elsif and else statements are optional, but the braces {} are mandatory The inverse function is unless
Conditional assignment
Syntax: condition ? then : else; Example:
$x = ($val <= $max) ? $val : $max;
Equivalent:
if ($val <= $max) {$x = $val;} else {$x = $max;}
16
17
The condition is tested before the statements are executed Using do statement while condition will always execute the statement once
Loop modifiers
next [label]; - go to the next loop iteration immediately, for the innermost (or labeled) loop block last [label]; - immediately break out of the innermost (or labeled) loop block goto label; - immediately go to a labeled line of code redo; start loop again without checking conditional statement
18
Loop modifiers
next last goto redo go to the next iteration of this loop break out of this loop go directly to a labeled line of code start loop again without checking cond.
6. Built-In Functions
Time functions Math functions
Time functions
Time is relative to January 1, 1970 UTC (Coordinated Universal Time) Time zone Local time Greenwich Mean Time (GMT = UTC)
Write a Perl script to parse each line, split the data and store each item in a hash table. Keep a count of each occurrence of each item (case insensitive). Print out an alphabetical list of items with the number of times each occurs in the list.
PDT-009679 September 2009 Slide 118
19
Relative time
Number of seconds since 01/01/1970 Syntax: time(); Example:
$starttime = time(); do some stuff $endtime = time(); $runtime = $endtime - $starttime; print "Total run time was $runtime sec.\n";
Converting time
Turns the time into something readable Syntax: localtime(); Returns a list: seconds, minutes, hour (023), day of the month, month (January = 0, etc.), year (minus 1900), day of the week (Sunday = 0, etc.), day of the year, Daylight Saving Time flag (true or false)
Math functions
sqrt(value) square root exp(value) exponential log(value) natural log sin(x) sine cos(x) cosine atan2(y, x) arc tangent
Example of localtime()
@timelist = localtime(); printf("Today is %d/%d/%d\n", $timelist[4]+1, $timelist[3], $timelist[5]+1900); Today is 2/21/2007
20
7. Regular Expressions
Patterns Wild cards Operators Matching data Altering data
Agenda
Part I
1. Introduction - Lab 1 2. Data Handling Break Lab 2a Lab 2b
A string consisting of
Regular characters Special characters
Agenda
Part III
7. Reg. Expressions Lab 7a / break RE functions Lab 7b
Matching strings
Part IV
8. Input & Output - Lab 8 / break 9. Subroutines - Lab 9 10. Wrap-up
For which of the following values for $name would each return true?
Bill, Mike, Mickey, Michael, Mikey
21
Regular expressions
Check if a string matches a pattern:
if ($name =~ /Mike/) { }
abracadabra
Matching operators
Syntax:
string =~ /RE/ string !~ /RE/
22
Repetition operators
Repetition operators (+ * ?) are "greedy" in that they match as much text as possible in the string Examples:
$str = "root:X:0:0:Operator:/:/bin/csh"; $str =~ /.*:/ root:X:0:0:Operator:/:/bin/csh
Shortcut examples
$str =~ /a\d\db/ a45b ac 5 ts ac 5 ts ab45a45bc xx 7 y xx 7 y 9a99ba aa7 8 bbb aa7 8 bbb
$str =~ /\w\s\d\s\w/
23
Grouping: ()
Use () to group multiple characters into one item; useful for repetition ops Examples:
$str =~ /(abc)+/ abc abcabcabcd
Alternatives: (|)
Separation of choices within a grouping Examples:
$str =~ /^(a|b)/ apple apple banana pine ant pineapple $str =~ /^(apple|pine)/
Anchors: ^ and $
Use ^ to anchor to the beginning and $ to anchor to the end of a string Examples:
$str =~ /^abc$/ abc allstars aabcc abcs abcc balls $str =~ /^a.*s/
24
^ $ () (x|y) \1-9 \d \D \s \S \w \W
Beginning / end anchors Grouping Alternatives Backreference Digit / non-digit Space / non-space Word character / non-wc
15-minute Break
Use the chart on the next page Construct a RE that matches the word in the table, but does NOT match the other words given in the code Use all of the special characters listed and any other characters you need
PDT-009679 September 2009 Slide 155 PDT-009679 September 2009 Slide 158
Instructions
First word none Last word Case insensitive First word First word, white space optional Preceeding zeros optional Case insensitive, end of line File is variable
Special characters
^ (as anchor) ( ) + [ ] { } $ (as anchor) \s + \b +
^ (as anchor)
25
Match function
Syntax: m/RE/ Example:
if ($line =~ m/status.*ok/) { }
Substitution function
Syntax: s/RE/newtext/options Examples:
$str =~ s/a/b/; $str =~ s/^\s+//; $str =~ s/name:[\s]+\w+/bill/;
Syntax variations
Examples:
if ($line =~ m/status.*ok/) { } if ($line =~ m:status.*ok:) { } if ($line =~ m[status.*ok]) { }
Substitution options
i, o, g same as match /re/newtext/e evaluate first Examples:
$str =~ s/abc/xyz/ig; $str =~ s/date/&getDate()/e;
Match options
/re/i matches irrespective of case /re/o compiles RE only once /re/g matches globally (multiple) Example:
while ($line =~ /Error/ig) { }
Match tagging
m/RE/; - use RE to define the tag reference variables $1 through $9 Stores in internal variables; available until next evaluation; reference from left to right; can nest tags Examples:
m/((\w+),\s*(\w+))/; $fn = $3; $ln = $2; $name = "$3 $2";
26
Substitute tagging
s/RE/newtext/; - use RE to define the tag reference variables $1 through $9 Stores in internal variables; available until next evaluation; reference from left to right; can nest tags Examples:
$name =~ s/((\w+),\s*(\w+))/$3 $2/;
Evaluation example
@list = (1, 2, 3); foreach $item (@list) { $item =~ s/(\d+)/$1**2/e; print "$item "; } > 1 4 9
PDT-009679 September 2009 Slide 168
RE Functions: Review
m/RE/ is the default function Options: i (irrespective of case), o (compile once), g (global), e (evaluate first) s/RE/newtext/options will substitute use RE with grouping to define the tag reference variables $1 through $9 list2 = grep /RE/, list1; is a function that uses regular expressions
PDT-009679 September 2009 Slide 171
Part I:
Print out only the words that start with "error" or "error:" Do not print the word "Errors" Ignore case
27
Agenda
Part III
7. Reg. Expressions Lab 7a / break RE functions Lab 7b
Part IV
8. Input & Output - Lab 8 / break 9. Subroutines - Lab 9 10. Wrap-up
Agenda
Part I
1. Introduction - Lab 1 2. Data Handling Break Lab 2a Lab 2b
Standard filehandles
Part II
3. Quoting Text - Lab 3 4. Advanced Printing - Lab 4 / break 5. Flow Control - Lab 5 6. Built-In Functions - Lab 6
Filehandles are identifiers that represent a particular instance of opening a file until it is closed STDIN (default is keyboard) STDOUT (default is monitor) STDERR (default is monitor)
28
Old style:
open (INH, $myfile") || die "Error"; What if $myfile is >weirdo<?
Examples:
open ($readh, -|, /bin/ps elf) or die Error: $!;
false (0) if it failed true (not 0) if it succeeded This is the same for all uses of open
Old style:
open (FH, cmd opts|);
Examples:
open ($writeh, |-, /usr/lib/sendmail -t oi) or die Error: $!; # use: print $writeh "From:, To:, Cc:, Subject:; mail is sent upon close
If the file exists, it will be overwritten, unless To open a file in read/write mode, use +< To empty the file first, use +>
Old style:
open (FH, |cmd opts);
Closing a file
Syntax: close (filehandle); Examples:
close ($fh);
Old Style:
close (LOG);
29
Deleting files
Syntax: unlink filename [, ]; Examples:
unlink $tmpfile; unlink @filelist;
This is generally preferable to a system call (system "rm $tmpfile";) since those are platform-specific
PDT-009679 September 2009 Slide 189
Renaming files
Syntax: rename oldname, newname; Examples:
rename $oldname, $newname; rename ($tmp, "$tmp.old");
Links in UNIX
A symlink (soft link) "points" to a file, directory or other symlink A hard link is another name for an existing file or directory UNIX examples:
> ln s xyz mylink (soft) > ln xyz mylink (hard)
Example:
if (! f $filename) { print "$filename not found!\n"; }
PDT-009679 September 2009 Slide 188
30
Creating a link
Syntax:
hard: link filename, linkname; soft: symlink filename, linkname;
File statistics
Syntax: stat (filename or filehandle); Returns an array of values related to the argument
0 Device where the file resides 1 Inode number 2 File mode (type and permissions) 3 Number of hard links to the file 4 User ID of owner 5 Group ID of group 6 The device type 7 The file's size (bytes) 8 When the file was last read 9 When the file was last edited 10 When inode was last changed 11 Preferred block size for I/O 12 The number of blocks allocated
Examples:
link ($theFile, $newLink); symlink "/tmp/datafile.dat", $newLink;
File statistics
Example:
@data = stat ("datafile.dat");
Example:
($dev, $inode, $mode, $nlink, $uid, $gid, $type, $size, @rest) = stat(INPUT);
Autoflush: $|
Output is buffered by default, turn this off by setting autoflush ($|) to true Example:
$| = 1; print "This is a test\n";
This is especially useful if text is being printed without the \n and computations are done before more printing on the same line
PDT-009679 September 2009 Slide 194
31
Directory I/O
Opening directories Reading directories Closing directories Making directories Changing the working directory
Opening directories
Syntax: opendir (dirhandle, dirPath); Examples:
opendir (my $dirh, $dirname); opendir (my $tmph, "/tmp");
Reading directories
Syntax: readdir (dirhandle); Returns: list of file names (relative) Examples:
opendir (my $dirh, "/tmp"); @list = readdir($dirh); # all files @list2 = grep(!/^\./, @list) # non-hidden files
32
Closing directories
Use close for files and closedir for directories, though both are the same Syntax: closedir (dirhandle); Example:
closedir ($dirh);
Making directories
Syntax: mkdir (dirname, permissions); Examples:
mkdir ($dirname, 0777); mkdir ("/tmp/scripts", 0755);
Miscellaneous I/O
Changing permissions Changing ownership and groups Globbing
Note: don't forget to add the 0 on the front of the permissions bits to make them octal numbers; the umask will affect the final permissions
Changing permissions
Syntax: chmod permissions, filename [, ]; Examples:
chmod 0755, $mydir; chmod 0777, @filelist; chmod 0544, $filename, $dirname;
Note: don't forget to add the 0 on the front of the permissions bits to make them octal numbers; is not recursive in directories
33
Changing ownership
Syntax: chown uid, gid, filename [, ]; Examples:
chown $uid, $newGid, $myfile; chown $newUid, $newGid, @fileList; chown $uid, $newGid, $filename;
To see hidden files, you must specify them explicitly. In UNIX, hidden files have filenames beginning with a period:
@hiddenfiles = <.*>; # only hidden
Note: only the superuser (root) can change the owner; this function can be used to change the group
Note: that will include "." (current) and ".." (parent) directories.
Note: the globstring may contain shell wildcards, not regular expressions
PDT-009679 September 2009 Slide 213
Globbing function
Another way is to use the glob function Syntax: glob(globstring) Examples:
@textfiles = glob("*.txt"); while (glob("*.data")) { }
Note: the globstring may contain shell wildcards, not regular expressions
PDT-009679 September 2009 Slide 214 PDT-009679 September 2009 Slide 217
34
Lab 8: Sample output Part A: lab8a.txt lab8b.txt Part B: 5 3 2 3 Candy Gum Key chain T-shirt
Write a routine to list all of the files that end with ".txt" in the current directory
PDT-009679 September 2009 Slide 218
15-minute Break
9. Subroutines
Writing subroutines Local variables Passing arguments Returning values
35
Writing subroutines
A subroutine
is a section of code has a name can have data passed into it can have local variables can pass data back to the caller is great for organizing and reusing code
Subroutine shortcuts
The example subroutine could be shortened to: sub multiply {$_[0] * $_[1];} This will run a bit faster, but isn't clear $_[0] is the first element of the @_ array, which is the first argument passed into the subroutine $_[1] is the second element passed in
Example subroutine
sub multiply { my ($value, $multiplier) = @_ ; return $value * $multiplier; } Calling this subroutine: $answer = &multiply(27, 30); print "$answer times two is ", &multiply($answer, 2), "\n";
Local variables
Variables in Perl are global by default You can declare local variables with my Including use strict; will enforce this. Variables declared with my are only visible in the block in which it is defined (and its subblocks) Inner blocks may define the same variable name without harming outer ones
PDT-009679 September 2009 Slide 229
36
Passing arguments
Argument are passed by value sub sumArray { my (@a) = @_; my $total; my ($i); foreach $i (@a) {$total += $i;} print "$total\n"; }
Passing arguments in
This argument order is OK: sub payrange { my ($low, $high, @people) = @_; } This argument order is NOT: sub payrange { my (@people, $low, $high) = @_; }
Calling subroutines
Syntax:
subName(argList[, ]); subName argList[, ]; &subName(argList[, ]); &subName argList[, ];
Examples:
&subArray(@list); subArray $a,$b,$c;
PDT-009679 September 2009 Slide 233 PDT-009679 September 2009 Slide 236
37
Prototypes
Prototypes are a way to enforce quantity and types of arguments to prevent problems Syntax: sub name(prototype); Examples:
sub multiply($$); sub proc_rpt($$;$$$); # 2 scalars # 2-5 scalars
Returning hashes
sub listcustomers() { # as a hash return (owner=>"jane", admin=>"john"); } -orsub listcustomers() { my %results; my $name; return ($name, %results); } # the hash # must be # last
Returning values
All subroutines return something, but it doesn't have to be used Syntax: return value; Example:
sub multiple { my ($a, $b) = @_; return ($a * $b); }
38
Subroutines: Review
Arguments are passed in via @_ Array and hash data are "unwound" and should be passed at the end of the list (or use references) Any number of args can be passed and any number of vals can be returned The default return value is the last expression value in the subroutine The return value can be ignored
PDT-009679 September 2009 Slide 246
References example
$aref = \@array; $href = \%hash; &refex($aref, $href); sub refex { my $ref1 = $_[0]; my $ref2 = $_[1]; while (($k, $v) = each %$ref2) { push (@$ref1, $v); } }
Write the subroutine "askproduct" which should ask the user (from STDIN) for the name of a single product Write the subroutine "printproduct" which should accept any number of product names as arguments and print one per line:
Item: productname is in stock
Write a subroutine "listfruit" that accepts the hash of fruit/quantity pairs given and returns a list of just the fruit names Use local variables within the subroutine Write the main code in the same file to call your subroutine and print what it returns
PDT-009679 September 2009 Slide 248
39
Advanced Perl
The advanced course material is on-line Find it at http://perl.intel.com The best way to learn Perl is to experiment and look at code others have written
10. Wrap-up
References Advanced Perl Course feedback
Course feedback
Please fill-out the Intel University course feedback survey on-line If you have additional comments, please email them to the course owner
matthew.s.jones@intel.com
References
In UNIX at Intel: perldoc f <function> or perldoc <module> Lots of books: look at Amazon.com Lots of web sites: go to perldoc.perl.org or do a Google search for "Perl" Lots of expertise at Intel, just ask around and someone will help; look for people with Perl books on their desks!
PDT-009679 September 2009 Slide 252
40