打印真值表到odt文件

时间:2018-03-08 08:06:04

标签: perl openoffice-writer odt

我想将真值表打印到adt文件中的表格中,得到一个程序,但我不知道如何获取值或打印到odt文件的值,这个程序只是在屏幕上打印结果!

sub truth_table {
    my $s = shift;
    #print "$s\n";
    my  @vars;
    for ($s =~ /([a-zA-Z_]\w*)/g) {
        push @vars, $_ ;

    }
    #print "$s\n";
    #print "$_\n";
    #print Dumper \@vars;
    #print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n";
    #print Dumper \@vars;
    @vars = map("\$$_", @vars);
    $s =~ s/([a-zA-Z_]\w*)/\$$1/g;
    $s = "print(".join(',"\t",', map("($_?'1':'0')", @vars, $s)).",\"\\n\")";
    $s = "for my $_ (0, 1) { $s }" for (reverse @vars);
    eval $s;
}
truth_table 'A ^ A_1';

1 个答案:

答案 0 :(得分:1)

使用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

但是,我会用Python宏来解决LibreOffice中的这个问题。 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,

enter image description here

以这种方式使用product基于Creating a truth table for any expression in Python

可以在https://wiki.openoffice.org/wiki/Python找到有关Python-UNO的更多文档。