Presentation is loading. Please wait.

Presentation is loading. Please wait.

Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group.

Similar presentations


Presentation on theme: "Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group."— Presentation transcript:

1 Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - matt@xndev.com Presented to the West Michigan Perl User’s Group

2 Why use Perl? ● Discuss

3 Getting Perl ● www.activestate.com – The easy way to get started in Windows ● www.cpan.org (Comprehensive Perl Archive Network) – If you have Linux, chances are you have Perl ● Both support modules for almost everything imaginable.

4 My first Perl script #!/usr/bin/perl -w use strict; print "Hello, world\n";

5 Variables in Perl ● Scalars start with a $ ex: $foo ● Arrays start with a @ ex: @foo ● Hashs (Associative arrays) start with % ex: %foo ● By convention file handles are UPPERCASE (no funny character). ● “my” gives variable lexical (local) scope. Use this unless you have reason for some other scope.

6 Scalars ● A Scalar begins with a $ ● A Scalar holds a single string, number or reference. ● Unitialized scalars are undef. ● Examples: – my $num = 3.1412; – $str = "This is a string";

7 Type Safe ● Perl is a loosely-typed language ● To make a string, evaluate the scalar in string context – Example: if ($a eq ‘Fifty’) { do_stuff($a); } ● To make a number, evaluate as a number – Example: if ($a == 50) { do_stuff($a); } ● Conversion is like ATOI ● To guarantee output, use prinft or sprintf

8 Some control structures ● Use {} (Curlies) to declare what your control strucuture is working with. Like BEGIN/END in PL/SQL or Pascal. ● Usual “if”-”elsif” (note missing e), “while”, and “for” structures. ● Also supports “unless” (!if), “until” (!while), and foreach strucutures. ● “next;” is like “continue;” in C. ● “last;” is like “break;” in C.

9 Boolean context ● The scalars: “” (null string), 0, “0”, and undef evaluate to false, everything else evalutates to true. ● Lists are put into scalar context, then evaluated for truth value. Zero length lists, and undef arrays evalute to false, all other lists are true.

10 Some operators ● Perl supports the usual +,-,*,/,%,++,-- (add, substract, multiply, divide, modulo, increment, decrement). ●. (period) concatenates strings. ● C style “+=”, “.=” etc. are supported. ● Use ==, !=, >, >=, <, <= to compare numbers ● Use eq, ne, gt, ge, lt, le to compare strings ● All the usual operators are available, but the syntax may be weird.

11 Basic I/O ● STDIN is a file ● To read from a file, do this: my $str = ; Control-Z is the EOF symbol on windows ● To re-direct STDIN from a file, do this: UNIX: perl scriptname.pl < in.txt Win: type in.txt | perl scriptname.pl ● To loop until EOF, do this: while (my $str = ) { }

12 Exercise 1) Write a program to add two scalar variables together and print the total. 3) Write a program to: – Read three numbers from the command line – Add them up – Print the total 2) Mod the program to also print an average

13 Arrays ● Array names begin with a @ ● Arrays are composites of scalars that are indexed with numbers beginning with 0. ● Arrays are named Lists. Subtle differences exist between Arrays and Lists. ● Examples: – my @stuff = (1,2,3);# use @ for the composite – $stuff[0] = 10;# use $ for a single element (scalar) – $stuff[99] = “Numbers and strings can be mixed”;

14 Iterating over a list for (my $i=0; $i< scalar(@a);$i++) { do_something($a[$i]); } for my $val (@a) { do_something($val); }

15 Push and Pop my @a; push (@a, 2); push (@a, 3); my $var = pop(@a); ● Remember, lists are automatically managed ● A stack using arrays is now trivial ● I sure wish I had this for the AP computer science A test!

16 Exercises 1) Write a program to: – Read three numbers from the command line – … Into a list – Loop and re-print the numbers – Print the total 2) Print the numbers in reverse – It’s ok to use a c-style for loop

17 Hashes ● Hash names begin with % ● Hashes are composites of scalars that are indexed with scalars. ● Hashes are unordered. ● Example: my %employee; $employee{"name"} = "Bill Day"; $employee{"SSN"} = "353-27-7625"; print $employee{"name"}, $employee{"SSN"} – - Outputs: Bill Day353-27-7625

18 Scalar vs List Context ● In an assignment, context is determined by left side of equal sign. ● An array in scalar context evaluates to length of the array: $len = @stuff; ● (parenthesis) will put a scalar into list context: ($thing) = @stuff; # assigns $stuff[0] to $thing. ● Psudeo-function “scalar” can be used to to force a list into a scalar. Example: scalar(@stuff);

19 Quotes in Perl ● 'Ordinary quotes' ● "Interpolated quotes - $vars exapanded\n", This is my favorite.. ● `execute a “shell”` command and return the result as a string. my $var = " test "; print " $var\n", '$var\n'; Outputs: test $var\n

20 Iterating over a hash #!/usr/bin/perl -w use strict;... my $key, $value, %hash;... while (($key, $value) = each %hash) { print $key $value "\n"; }

21 Pronouns in Perl ● $_ is the default variable ● Example: #!/usr/bin/perl -w use strict; my @array = ("a", "b", "c"); # the following 2 loops are equivalent foreach my $element (@array) { print $element; } foreach (@array) { print; }

22 Regular Expressions ● Much like SED ● if (/Bill Day/) # evaluate $_, true if it contains string. ● if ($var =~ /Bill Day/) # evalute $var for string. ● $var =~ s/Bill/William/; # substitue the 1 st occurance of “Bill” with “William” in $var. ● Lots of special characters:., ?, *, +, (, ), [, ], | ^, \, {, }, ● One of the most powerful features of Perl. ● Unfortunately beyond the scope of this talk.

23 I/O in Perl ● open IN, "name"; # open “name” for reading. ● open HANDLE, "<name"; # same thing. ● open OUT, ">output”; # create or truncate file for output. ● open LOG, ">>logfile "; # append or create file for output. ● close HANDLE; # When done with file. ● All the POSIX “C” style stuff works.

24 I/O in Perl Continued ● # (diamond operator) to read a line from the file. ● print HANDLE "string"; # prints to file. Note: no comma between HANDLE and string. ● <> with no handle reads each file given on the command line, else if command line blank STDIN. Just like you want your standard Unix utility to do.

25 Errors and warnings ● die "meltdown in progress"; # message to STDERR for fatal errors (exits program). ● warn "your shoe is untied."; # message to STDERR for non-fatal warnings.

26 Putting it all together #!/usr/bin/perl -w use strict; open ORIGINAL, "<original " or die " cannot open 'original': $!"; while ( ) { s/William/Bill/g; # substitute Bill for William globally print; } close ORIGINAL;

27 Where to get help ● In shell: perldoc perl ● In shell: perldoc perlre ● www.perl.com ● www.cpan.org ● www.activestate.com ● grand-rapids.pm.org

28 Review ● Perl is the premier open source high performance cross platform enterprise class object oriented language that holds together the world wide web. ● There's more than one way to do it – TMTOWTDI (Pronounced “Tim-Toady”) ● Perl makes Easy things easy, and hard things possible. ● Questions?

29 Exercises: 1) Create a hash; write a program to loop through a hash and print all hash pairs. 2) Write a program to read some numbers in from STDIN. stopping when the user types in 'quit', and print the total. 3) Write a program to read in some words from the command line, replacing Matthew with Matt, and re- print the words back onto the command line.


Download ppt "Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group."

Similar presentations


Ads by Google