#!/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"; } }