用Capture::Tiny得到eval的结果,然后根据https://stackoverflow.com/a/4226073/5100564将字符串拆分成二维数组。
use Capture::Tiny 'capture_stdout';
sub truth_table {
#...the rest of your code here...
my $stdout = capture_stdout {
eval $s;
};
return $stdout;
}
$truth_string = truth_table 'A ^ A_1';
my @truth_array;
foreach my $line (split "\n", $truth_string) {
push @truth_array, [split ' ', $line];
}
foreach my $line (@truth_array) {
foreach my $val (@$line) {
print $val;
}
print "\n";
}
为此,我基于What's the easiest way to install a missing Perl module?执行了以下命令
cpan
install Capture::Tiny
但是,我会在 LibreOffice 中使用 Python 宏来解决这个问题。 APSO 方便输入和运行这段代码。
import uno
from itertools import product
def truth_table():
NUM_VARS = 2 # A and B
columns = NUM_VARS + 1
rows = pow(2, NUM_VARS) + 1
oDoc = XSCRIPTCONTEXT.getDocument()
oText = oDoc.getText()
oCursor = oText.createTextCursorByRange(oText.getStart())
oTable = oDoc.createInstance("com.sun.star.text.TextTable")
oTable.initialize(rows, columns)
oText.insertTextContent(oCursor, oTable, False)
for column, heading in enumerate(("A", "B", "A ^ B")):
oTable.getCellByPosition(column, 0).setString(heading)
row = 1 # the second row
for p in product((0, 1), repeat=NUM_VARS):
result = truth_function(*p)
for column in range(NUM_VARS):
oTable.getCellByPosition(column, row).setString(p[column])
oTable.getCellByPosition(column + 1, row).setString(result)
row += 1
def truth_function(x, y):
return pow(x, y);
g_exportedScripts = truth_table,
这样使用product是基于Creating a truth table for any expression in Python。
更多关于 Python-UNO 的文档可以在https://wiki.openoffice.org/wiki/Python找到。