File: Runner.pm

package info (click to toggle)
libpegex-perl 0.75-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 908 kB
  • sloc: perl: 3,288; makefile: 43; sh: 2
file content (50 lines) | stat: -rw-r--r-- 932 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Runner;
use Mo;

has args => [];
has callback => ();

sub run {
    my ($self, $calc) = @_;
    $self->callback($calc);

    return $self->run_file if @{$self->{args}};

    while (1) {
        print "\nEnter an equation: ";
        my $expr = <> || '';
        chomp $expr;
        last unless length $expr;
        $self->calc($expr);
    }
}

sub run_file {
    my ($self) = @_;
    my $file = shift(@{$self->args});
    open IN, "<", $file or die "Can't open '$file' for input";
    while (<IN>) {
        next if /^(?:#|$)/;
        chomp;
        $self->calc($_);
    }
}

sub calc {
    my ($self, $expr) = @_;
    my $result = eval { $self->callback->($expr) };
    if ($@) {
        warn $@;
        return;
    }
    print "$expr = $result\n";

    # Double-check answer:
    $expr =~ s/\^/**/g;
    $expr =~ s/--/- -/g;
    my $want = eval $expr;
    print "  EXPECTED $want\n"
        if $result ne $want;
}

1;