Wednesday, March 26, 2003

Subroutines (S&P -- Chapter 4)

As in C and C++, perl has the concept of a function or subroutine, as they are called in perl. For example, here is a simple subroutine that adds two numbers and returns the result:


#!/usr/bin/perl -w

use strict;

sub sum {
	my ($num1, $num2) = @_;

	return $num1 + $num2;
}

print &sum(12, 43), "\n";

my ($v1, $v2) = (100, 10);
print &sum($v1, $v2), "\n";

my @a = (1, 2);
print &sum(@a), "\n";


There are several important points about the above subroutine that you should notice:

The above subroutine is a bit restrictive in that it only sums up two numbers. We can make our subroutine more flexible by allowing it to sum up a variable number of arguments:


#!/usr/bin/perl -w

use strict;

sub sum {
	my $sum = 0;

	print "No numbers given!\n" if ! @_;
	for (@_) {
		$sum += $_;
	}
	$sum;
}

print &sum(12, 43, 67, 98), "\n";

my ($v1, $v2) = (100, 10);
print &sum($v1, $v2), "\n";

my @empty = ();
print &sum(@empty), "\n";

print &sum(1..100), "\n";


Again, there are several things to note about the above script:

Hashes (S&P -- Chapter 5)

Hashes in perl are roughly equivalent to the map class of C++ standard library. They associate scalar strings (called a key) to their respective values (typically, another scalar). Unlike the map class, perl's hashes are not self-ordering. By default, the order in which you place the elements into the hash may be different than the order in which you can retrieve them. Perl does provide a way to retrieve the keys in order, but you have to do so manually, as seen below:


#!/usr/bin/perl -w

use strict;

my %ip_to_host = ("134.153.48.1", "garfield", "134.153.48.2", "mirror",
	 "134.153.48.3", "phobos", );

$ip_to_host{"134.153.48.4"} = "deimos";
$ip_to_host{"134.153.48.10"} = "irma";

while (my ($ip, $host) = each %ip_to_host) {
	print "Hostname $host has IP address $ip\n";
}
print "\n";
delete $ip_to_host{"134.153.48.2"};	# Get rid of 'mirror' host.

# Display the hosts again, this time in sorted order.  Note
# that the sorting is lexicographic.  So host irma's IP
# address appears after garfield but before phobos
#
for (sort keys %ip_to_host) {
	print "Hostname $ip_to_host{$_} has IP address $_\n";
}

my %host_to_ip = reverse %ip_to_host;
printf "\nGarfield has ip address $host_to_ip{'garfield'}\n";


The above script demonstrates many aspects of hash types in perl.

One final note about hashes is that hashes are not interpolated inside double quotes, like scalars and arrays. Therefore, you cannot, for example, display the keys/values of a hash variable by saying print "The hash table is %h\n". The %h will be interpreted literally.

Last modified: Wed Mar 26 15:50:26 2003