Transcript Slide15

Advance Topics
Topics
•
•
•
•
Packages
Launching Programs
Sockets
Using Unix DBM
Packages
• Every program has a main package.
• A program can use other packages
– use <name>;
• The programmer can also define packages.
– package <name>;
• The rest of the file is the body of the
package.
• The name of the file is <name>.pm
Packages (cont.)
• Each package has its own namespace.
– Reduces the risk of name conflicts.
• Functions: <name>::<function name>
– e.g. String::length
• Global vars: <var symbol><name>::<var>
– e.g. $String::foo
• my can be used to prevent access:
Package private;
my $private_var;
Launching Programs
• Almost all programming languages allow
their programs to call subprograms.
• Perl is no exception.
• Perl has several ways to launch a program.
• Two most common are:
– backquote (`)
– system
• Perl also includes fork and exec.
backquote
• Place the name of the subprogram in (`).
• Synchronous execution.
• Return value is the output of the
subprogram.
• For example,
$date = `date`;
print “$date \n”;
system
• Pass subprogram’s name to system.
• Synchronous execution.
• Return value is the execution status of the
subprogram.
• Subprograms output is directed to
STDOUT.
• For example:
system(“date”);
Socket Communication
• Provides a powerful way to communicate
between computers, programs, etc.
• Based on the notion of clients and servers.
• Usage is similar to files:
– Programs read from and write to sockets.
• Supported by Perl’s Socket module.
– use Socket;
A Client/Server Example
Unix DBM
• Unix has a simple DataBase Management
(DBM) system.
• A DBM database is a list of key/value pairs.
• Structure similar to Perl’s hash.
• DBM databases are connected to hash.
• DBM provides persistent hashes.
DBM (cont.)
• A DBM database is stored in two files:
– <name>.pag: Stores the data.
– <name>.dir: Index into the .pag file.
• dbmopen is used to create and open DBM
databases.
• dbmclose breaks connection between hash
and database.
dbmopen/dbmclose
• dbmopen (<hash>, <dbname>, <mode>)
– e.g. dbmopen (%salaries, salary_db, 0666);
– e.g. dbmopen (%salaries, salary_db, undef);
• dbmclose (<hash>)
– e.g. dbmclose (%salaries);
An Example
dbmopen (%salaries, salary_db, 0666) ||
die “Could not open salary_db $!”;
print “Enter an employee’s name: ”;
while ($name = <STDIN>) {
chomp $name;
print “Enter the salary: ”;
$salaries{$name} = <STDIN>;
print “Enter an employee’s name: ”;
}
dbmclose (%salaries);