(1) For example,
use strict;
#
# h2q1.pl
# Bun Yue August 15, 2000
#
@ARGV < 2 && die "Usage: h2q1.pl
h2q1dat.txt h2q1out.txt\n";
open(IN, $ARGV[0]) || die "Can't open input
file $ARGV[0].\n";
open(OUT, ">$ARGV[1]") || die "Can't open
output file $ARGV[1].\n";
while ($_ = <IN>) {
chomp;
s/((.*?,){10}.*?),/\1)
or (/gi;
$_ = "($_)" if $_;
print OUT "$_\n";
}
close(IN);
close(OUT);
exit 0;
(2) For example,
use strict;
#
# h2q2.pl
# Bun Yue August 15, 2000
#
testReverseHash();
exit 0;
#
# Accept a hash %in and return a hash that
reverses the
# role of keys and values of %in. If
there are more
# than one key with the same values, then
the keys
# are separated by a '|' as values of the
return hash.
#
sub reverseHash {
my %in = @_;
my %out = ();
foreach my $key (keys
%in) {
if ($out{$in{$key}}) {
$out{$in{$key}} .= "|$key";
}
else {
$out{$in{$key}} = "$key";
}
}
%out;
}
# Test the hash.
sub testReverseHash {
my %in = ("abc", "1",
"def", "1", "hij", "2", "kkk", "1", "lmn", "2", "rst", "3");
print "Input hash:\n";
foreach my $key (sort
keys %in) {
print " $key => $in{$key}\n";
}
my %out = reverseHash(%in);
print "Output hash:\n";
foreach my $key (sort
keys %out) {
print " $key => $out{$key}\n";
}
}
(3) For example,
use strict;
#
# h2q3.pl
# Bun Yue August 16, 2000
#
testRandomPermutation();
exit 0;
#
# Return an array that is a random permutation
of the input array.
#
sub randomPermutation {
my @in = @_;
my @out = ();
while (@in > 0) {
push @out, splice(@in, int(rand(scalar
@in)), 1);
}
@out;
}
sub testRandomPermutation {
my @list = (1, 2, 3, 4, 5, 6, 7, 8,
9, 10);
my @result = ();
my $NUM_TEST = 5;
print "Input list: ";
foreach (@list) {
print "$_ ";
}
print "\n\n";
for (my $i=0; $i<$NUM_TEST; $i++)
{
print "Output list #" . ($i+1) . ":
";
@result = randomPermutation(@list);
foreach (@result) {
print "$_ ";
}
print "\n";
}
}