lib/Language/Zcode/Runtime/Input.pm untested

filter: Statementstmt 0.0% 0 / 37 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 74 CC 11 SCAR 35.6
CC
11
Cov
0%
input_stream
72.0
get_line_from_file
12.0
cleanup
6.0
CRAP 35.2
1 package Language::Zcode::Runtime::Input;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 Language::Zcode::Runtime::Input - handle (some) input to Z-machine
9
10 =DESCRIPTION
11
12 This package handles (some) input to the Z-machine.
13
14 It does need to call some print routines, but basically it handles
15 input streams.
16
17 =cut
18
19 # 10.2
20 use constant INPUT_KEYBOARD => 0;
21 use constant INPUT_FILE => 1;
22
23 sub setup {
24 input_stream(INPUT_KEYBOARD);
25 }
26
27 my $current_input_stream;
28 my $input_filehandle; # for reading commands from file
29
30 # select input stream
31 sub input_stream {
32 my ($stream, $filename) = @_;
33 # $filename is an extension (only used internally)
34 $current_input_stream = $stream;
35
36 if ($stream == INPUT_FILE) {
37 my $ok = 0;
38 my $fn = $filename || Language::Zcode::Runtime::IO::filename_prompt("-ext" => "cmd");
39 # filename provided if playing back from command line
40 if ($fn) {
41 if ($input_filehandle = new IO::File($fn)) {
42 $ok = 1;
43 # if name provided, don't print this message
44 Language::Zcode::Runtime::IO::write_text("Playing back commands from $fn...")
45 unless defined $filename;
46 } else {
47 Language::Zcode::Runtime::IO::write_text("Can't open \"$fn\" for playback: $!");
48 }
49 Language::Zcode::Runtime::IO::newline();
50 }
51 $current_input_stream = INPUT_KEYBOARD unless $ok;
52 } elsif ($stream eq INPUT_KEYBOARD) {
53 close $input_filehandle if $input_filehandle;
54 } else {
55 # XXX this sub doesn't exist
56 Language::Zcode::Runtime::IO::fatal_error("Unknown stream $stream");
57 }
58 }
59
60 # Return chomped line from a file
61 # Return undef and stop reading from the file if eof
62 # Also return undef if we're not supposed to be reading from a file right now
63 sub get_line_from_file {
64 my $s; # = "";
65 if ($current_input_stream == INPUT_FILE) {
66 $s = <$input_filehandle>;
67 if (defined($s)) {
68 # got a command; display it
69 # Chomp to avoid OS differences in \n
70 chomp $s;
71 } else {
72 # end of file
73 input_stream(INPUT_KEYBOARD);
74 # ADK returning "" instead of undef makes eof
75 # indistinguishable from an empty line that doesn't end the file
76 #$s = "";
77 }
78 }
79 return $s;
80 }
81
82 # End of program cleanup
83 sub cleanup {
84 close $input_filehandle if $input_filehandle;
85 # Don't need to do anything to screen input stream
86 }
87
88 1;