Perl Tk

Basic Constructs
o Perl Hello, World!
o Hello Again
o Scalar Variables
o Arrays
o Hashes
o Arrays and Hashes Together
o The Strict Pragma
Loops, Arguments, I/O
oWhile Loop
oEcho I
oEcho II
oEcho III
oEcho IV
oControl Constructs
oPostfix Control Constructs
oArgs I
oArgs II: The For Loop
oArgs III: The Foreach Loop
oArgs IV
oArgs V
o Environment I
o Environment II
o Turbo Hello, World
Files
o File Reader I
o File Reader II
oFile Reader III
oFile Copier
Functions
o Array Assignments
o Functions And Arguments
o Using Arguments I
o Using Arguments II
o Using Arguments III
Patterns
o Count Blank Lines I
o Count Blank Lines II
o Check C Programs
o Applet Viewer
o UID Lookup
o Link Finder I
o Link Finder II
o Link Finder III
o Apache Log Reader
Generating HTML
o HTML File Display
o Text to HTML Translator
o HTML Table Generator
References, Packages and Objects
o Perl References
o Simple Module
o Module Test Driver
o Simple Class
o Class Test Driver
Perl/Tk GUIs
o TK Buttons I
o TK Buttons II
o TK Color Buttons I
o TK Color Buttons II
o FTP Download GUI
Network Clients
o Email Address Client
o Web Page Parser
o FTP Synchroniz

Perl Hello, World!
use strict; # Prints the message using two different delimeters. print "Hello, world!\n"; print qq=Did you say "Hello?"\n=;
Hello Again
# Shows how single quotes differ from double quotes used in hello.pl print 'Greetings, small planet!\n'; print q/What's cooking?\n/;
Scalar Variables
# Various operations on scalar (string) variables. $fred = "Fred here"; $barney = 56; $sum = 10 + $barney; print 'The variable $fred' . " contains $fred.\n"; print "Sum is $sum.\n";
Arrays
# Simple array constructs. @fred = ("How", "are", "you", "today?"); print "\@fred contains (@fred).\n"; $mike = $fred[1]; print "$mike $fred[3]\n"; # The array name in a scalar context gives the size. $fredsize = @fred; print '@fred has ', "$fredsize elements.\n"; # The $#name gives the max subscript (size less one). print "Max sub is $#fred\n";
# Variables whose names begin with @ are arrays.
If @sue is an array, it is different variable from $sue. However, members of @sue are selected by $sue[$i].
#The construction $#arrname gives the maximum subscript of the array @arrname.

Hashes
# Simple hash constructs $fred{"with"} = "without"; $fred{"this"} = "that"; $fred{"mountain"} = "valley"; $fred{"left"} = "right"; print qq/$fred{"this"}\n/; @keys = keys(%fred); print "Keys are @keys\n"; # Initializer for %yard. %yard = ( red => 'brick', blue => 'sky', green => 'grass', yellow => 'dandelion' ); print "$yard{'blue'} $yard{'yellow'}\n";
# Variables whose names begin with % are hashes, which are essentially arrays subscripted by strings. As with arrays, %sue is a hash, and it is a different variable from $sue, though members of %sue are selected by $sue{$s}.
# The built-in function keys(%sue) returns an array of all the keys (subscripts) of the hash %sue.

Arrays and Hashes Together
# Arrays and hashes convert to each other, an array being taken as a list # of key, value pairs in order, a hash being flattend to such an array. # Key order of the hash will be arbitrary. # The => is just a glorified comma (which quotes its left arg). @alex = ( fred => 44, 'joe' => 2983, mike => -94 ); %heather = ('This', 'will', 'actually', 'work'); print "A: \@alex = (@alex)\n"; print "B: $heather{'This'} $heather{'actually'}\n"; %heather = @alex; print "C: [$heather{'fred'}] [$heather{'joe'}] [$heather{'mike'}] ", "[$heather{'This'}]\n"; $heather{'dingbat'} = 8822; $heather{'giggles'} = 33; @alex = %heather; print "D: @alex\n"; # Extras are empty string. %heather = ('a', 'b', 'c'); print "E: [$heather{'a'}] [$heather{'c'}]\n"; # Duplicate keys get the last value. %heather = ( 'brillig' => 74, 'snark' => 34, 'slithy' => 18, 'snark' => 99, 'beamish' => 48, 'brillig' => 1 ); print "E: [$heather{'brillig'}] [$heather{'snark'}] ", "[$heather{'slithy'}] [$heather{'beamish'}]\n";
The Strict Pragma
# Normally variables in perl need not be declared. This can be # changed with the following directive. use strict; # The my function declares the variable. my $fred; $fred = "I am Fred."; print "$fred Fred I am.\n"; # Declare and initialize. my $qty = 57; $qty = $qty + 10; print "We have $qty on hand.\n"; my @joe = (1, $qty, 2*$qty, $qty*$qty); print "$joe[0], $joe[1], $joe[2] and $joe[3]\n"; my %goombah; $goombah{'a'} = 'anaconda'; $goombah{'b'} = 'barracuda'; $goombah{'c'} = 'carbuncle'; print "a is for $goombah{'a'}, b is for $goombah{'b'} and ", "c is for $goombah{'c'}.\n";
While Loop
use strict; my $a = 5; while($a > 0) { print "$a "; $a--; } print "\n";
Echo 1
use strict; # Echo input to output. while(my $fred = <STDIN>) { print $fred; }
Echo 2
use strict; # Echo input to output, letting STDIN default. while(my $fred = <>) { print $fred; }
Echo 3
use strict; # Echo input to output, using $_ to collect the input line by default. while(<STDIN>) { print $_; }
Echo 4
use strict; # Echo input to output, using <> and $_ defaults. while(<>) { print; }
Control Constructs
use strict; # Read some lines, concat them together (separated by a space), and print them. # How exciting. Stops when it reaches the indicated count, the # end of file, or the line STOP! # Read the number. print "How many lines? "; my $num = <STDIN>; $num > 0 or die "Num must be positive. You entered $num"; # Read in the strings. my $accum = ""; my $sep = ""; while(my $line = <STDIN>) { chomp $line; if($line eq "STOP!") { last; } $accum = "$accum$sep$line"; if(--$num == 0) { last; } $sep = " "; } # Print what we got. print "$accum\n";
Several things to note:
  1. Scalar variables contain strings, but <, >, <=, >=, == and != can be used to compare them as numbers.
  2. The operators lt, gt, le, ge, eq, and ne are used to compare scalars as strings.
  3. chomp trims the line separator.
  4. last is like break in C.
  5. Using variable names inside double quotes is not just for output. It can be done anywhere double quotes are used.
Postfix Control Constructs
# Perl postfix conditionals (which are actually expression operators). # They follow what they control and don't use { }. use strict; # Read some lines. my $wasquit = 0; print "ctl2> "; while(my $line = <STDIN>) { chomp $line; print "Jones\n" if $line eq 'smith'; # Quitting is here. if($line eq 'stop') { print "That's better.\n" if $wasquit; last; } if($line eq 'quit') { $wasquit = 1; print "You must say stop if you want to quit.\n"; } else { $wasquit = 0; } print "$line to you!\n" if $line; print "ctl2> " unless $line eq 'sssh'; }
Args I
use strict; # This script simply prints its command line arguments, one per line. my $sub = 0; while($sub <= $#ARGV) { print "$ARGV[$sub]\n"; ++$sub; } print "[@ARGV]\n";
Args II: The For Loop
use strict; # Here's another way to print all the command line arguments. The perl # for loop is much like the C for loop. for(my $sub = 0; $sub <= $#ARGV; ++$sub) { print "$ARGV[$sub]\n"; } print "[@ARGV]\n";
Args III: The Foreach Loop
use strict; # Here is yet another way to print out all the arguments. The foreach # command loops through the members of an array and assigns some variable # to each one in turn. foreach my $arg (@ARGV) { print "$arg\n"; } print "[@ARGV]\n";
Args IV
# And, yet another way to print the command-line arguments. This uses the # shift operator, which removes the first member of the array and returns # it. After the loop is finished, the array is empty. while($item = shift @ARGV) { print "$item\n"; } print "[@ARGV]\n";
Args V
# This prints the arguments in the same way as args4, but it re-constructs # the list. (Of course, if you really needed the list again, you probably # wouldn't print it this way, but it demonstrates the push operator.) while($item = shift @ARGV) { print "$item\n"; push @newargs, $item; } print "[@newargs]\n";
The push operator adds an item to the end of the array, just as removes one from the front. The array @newargs, like all perl arrays, is initially empty. So, if the script is run as

perl args5.pl How are you perl

this is how the arrays change:
@newargs@ARGV
How are you perl Before the loop starts.
How are you perl After the first iteration.
How are you perl After the second iteration.
How are you perl After the third iteration.
How are you perl After the fourth iteration.
Environment I
use strict; # This script prints out its environment varibles. Under Unix, its output # looks a lot like the results of the printenv command. my @keys = keys(%ENV); while(my $key = shift @keys) { print "$key=$ENV{$key}\n"; }
Environment II
use strict; # This script prints out its environment varibles in sorted order. foreach my $key (sort keys(%ENV)) { print "$key=$ENV{$key}\n"; }
Turbo Hello, World
use strict; # Prints the message using two different delimeters. print "Hello, world!\n"; print qq=Did you say "Hello?"\n=;