130 likes | 276 Views
Joseph Harnish Western Michigan VMware Users Group. Intro to Perl. Why Perl?. Perl is used by many organizations. Perl is available on Windows and Linux. VMware has a SDK with Perl modules. What we are going to cover. Datatypes Regular Expressions File I/O. Basic Datatypes.
E N D
Joseph Harnish Western Michigan VMware Users Group Intro to Perl
Why Perl? • Perl is used by many organizations. • Perl is available on Windows and Linux. • VMware has a SDK with Perl modules.
What we are going to cover. • Datatypes • Regular Expressions • File I/O
Basic Datatypes • Scalar – Scalars hold a single item. Scalars are denoted by a $ prefix on the variable. • Array – Arrays hold a collection of numerically index scalars. They are prefixed by an @. • Hash – Hashes are collections of key value pairs. They act like arrays but are referenced by keys.
Scalars can be used for numerical calculations, string manipulation, etc. Scalars
Code example my @array = (“one”, “two”, “three”, “four”); $array[4]=”five”; for (my $i=0; $i<=4;$i++){ print “$array[$i]\n”; } # a simpler loop foreach (@array){ print “$_\n”; } Arrays
Code Example: #initialize has my %simpsons=(‘Father’=>’Homer’, ’Mother’=>’Marge’,’Son’=>’Bart’, ‘Daughter’=>’Lisa’); $simpsons{‘Baby’}=’Maggie’; foreach( keys %simpsons){ print “$_ =>$simpson{$_}\n”; } Hashes
Regular Expressions • Way of matching a pattern • Patterns consist of literal characters, character classes and quantifiers. • Character classes will match when any character in class is present. \s whitespace, \w word character, \d digit • Quantifiers tell how much items are needed for a match.
Quantifiers • ? = 0 or 1 • + = 1 or more • * = 0 or more • {n} = n times • {n,m} = between m and n times (inclusive)
Pattern match operators • =~ binds a match or substitution to a scalar it is searching. • /pattern/ match operator—looks to see if a variable contains specified pattern • s/pattern/replace/ substitution operator—replace anything that matches a pattern with replace string • Useful flags can be added at the end of the match or substitution to modify its behavior
Pattern match operators (cont) • Case-insensitive flag-i matches regardless of capitalization • Global flag-g finds or replaces all occurrences, not just the first one. • $name=~/bob/i; #matches bob, Bob, BOB, etc. • $name=~s/bob/Robert/gi; #replaces all variants of bob with Robert.
my $string=’743-5322 233-2355 23-452’; print “String contains at least one phone number” if ($string=~/\d{3}\-\d{4}/); while($string=~/(d{3}\-\d{4})/){ print “$string\n”; } Match Example
search.cpan.org www.perlmonks.org www.vmware.com Additional Resources