-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplang
executable file
·99 lines (76 loc) · 2.52 KB
/
plang
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env perl
# example Plang interpreter script
#
# see the `plang_builtin` script for a demonstration of adding a builtin function
use v5.16;
use warnings;
use strict;
use feature 'signatures';
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
use Getopt::Long qw(GetOptionsFromArray);
# use Plang
use Plang::Interpreter;
my $usage = <<"USAGE";
usage: $0 [-f <file>] [-m <path>] [code]
If the `-f <file>` switch is provided, code will be executed from that file.
Otherwise, if any command-line arguments remain after all switches are
processed, they will be used as the code. If there were no arguments, the
stdin stream will be read.
Switches:
-f|--file <file>
Execute contents of <file> instead of command-line arguments or stdin.
-m|--modpath <path>
Add <path> to list of module paths. Multiple -m can be provided to append
subsequent paths to the list.
USAGE
sub getopt_from_array($opt_args, $result, $config, @opts) {
# emitting errors as Perl warnings instead of using die, weird.
my $opt_error;
local $SIG{__WARN__} = sub {
$opt_error = shift;
chomp $opt_error;
};
Getopt::Long::Configure(@$config);
GetOptionsFromArray($opt_args, $result, @opts);
return ($opt_args, $opt_error);
}
# The plang() subroutine can used to interpret a string or the STDIN stream,
# depending on whether a string argument was passed or not.
sub plang($text, %opts) {
# add default modules/ path relative to location of this script
push $opts{modpath}->@*, "$RealBin/../modules/";
# create Plang object
my $plang = Plang::Interpreter->new(
debug => $ENV{DEBUG},
modpath => $opts{modpath},
);
if ($opts{file}) {
# if -f or --file was specified, interpret contents of a file
my $content = $plang->load_file($opts{file}, rootpath => 1);
return $plang->interpret_string($content);
} elsif (defined $text and length $text) {
# if a string argument was provided, interpret the string
return $plang->interpret_string($text);
} else {
# otherwise interpret the standard input stream
return $plang->interpret_stream(*STDIN);
}
}
sub main() {
my %opts;
my ($opt_args, $opt_error) = getopt_from_array(
\@ARGV,
\%opts,
['bundling'],
'file|f=s',
'modpath|m=s@'
);
if (defined $opt_error) {
print "$opt_error -- $usage\n";
exit 1;
}
# interpret plang script and exit using returned value
exit int (plang("@$opt_args", %opts) // 0);
}
main;