Abstract Data Types (ADT)

This page is under construction. Please come back later.
#!/usr/bin/env perl
use utf8;
###############################################################################
# This program demonstrates the Stack ADT
#
# Copyright © 2021 Richard Lesh. All rights reserved.
###############################################################################
use Error::Simple;
use Nice::Try;
use Utils;
use strict;
use warnings;
package IntegerStack {
# Internal representation for the stack is a list
sub new {
my $class = shift @_;
my $self = {};
$self->{'stack'} = [];
bless $self, $class;
return $self;
}
sub pop {
my ($self) = @_;
if (scalar(@{$self->{'stack'}}) == 0) {
die Error::RuntimeException->new("Can't pop on empty stack!");
}
return pop(@{$self->{'stack'}});
}
sub push {
my ($self, $value) = @_;
push(@{$self->{'stack'}}, $value);
}
sub peek {
my ($self) = @_;
if (scalar(@{$self->{'stack'}}) == 0) {
die Error::RuntimeException->new("Can't peek on empty stack!");
}
return $self->{'stack'}->[scalar(@{$self->{'stack'}}) - 1];
}
}
MAIN:
{
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
binmode(STDIN, ":utf8");
my $stack = new IntegerStack();
for (my $x = 1; $x <= 10; ++$x) {
$stack->push($x);
}
try {
print $stack->peek(), "\n";
for (my $x = 1; $x <= 11; ++$x) {
print $stack->pop(), "\n";
}
} catch (Error::RuntimeException $ex) {
print $ex, "\n";
} catch (Error::Simple $ex) {
print "Unknown Exception!\n";
}
}
Output
$ perl ADTStack.pl
10
10
9
8
7
6
5
4
3
2
1
Can't pop on empty stack! at ADTStack.pl line 30.
#!/usr/bin/env perl
use utf8;
###############################################################################
# Simple first program.
#
# Copyright © 2020 Richard Lesh. All rights reserved.
###############################################################################
use strict;
use warnings;
MAIN:
{
print "Hello, world!\n";
}
Output
$ perl HelloWorld.pl
Hello, world!
#!/usr/bin/env perl
use utf8;
###############################################################################
# Simple first program.
#
# Copyright © 2020 Richard Lesh. All rights reserved.
###############################################################################
use strict;
use warnings;
MAIN:
{
print "Hello, world!\n";
}
Output
$ perl HelloWorld.pl
Hello, world!
Questions
Projects
More ★'s indicate higher difficulty level.
References
- [[Perl Language Reference]]
- [[Comprehensive Perl Archive Network (CPAN)]]
- [[Beginning Perl]], Simon Cozens
- [[Perl Monks Tutorials]]
Pure Programmer


