c++ - 如何从 C++ 调用 perl?

标签 c++ perl dev-c++

我有一个 perl 程序,用于处理特定格式的大型税务文件。我已经从该 perl 准备了一个 exe 文件,它用作 Windows 控制台应用程序。但对于学术用途,该应用程序需要用更好的 GUI (C++) 编写。
我不可能用 C++ 再次重写整个代码(由于时间限制)。
有没有办法从 C++ GUI 获取文件,使用 perl App(.pl 或 .exe)进行处理,然后再次使用 C++ Window 显示输出。
欢迎任何其他更好的选择。

最佳答案

这是一个使用 Prima 的简单示例选择一个输入文件并对其运行简单的报告。

希望它说明您不需要需要重写整个 Perl 应用程序来添加简单的 GUI。前几个函数完成处理文件和生成报告的实际工作。应用程序的这一部分不需要了解有关 GUI 的任何事情。

最后一部分提供了一个 GUI 包装器。这是应用程序中唯一需要处理 Prima 的部分。

use strict;
use warnings;

# This is the guts of the report.
# It takes a filehandle and does some serious number crunching!
# Just kidding. It counts the occurrences of vowels in a text
# file. But it could be doing any serious reporting work you want.
# 
sub get_data_from_file {
  my ($fh) = @_;
  my %vowels;
  while (<$fh>) {
    $vowels{uc($_)}++ for /([aeiou])/gi;
  }
  return \%vowels;
}

# Format report in Pod because personally I find
# that a bit easier to deal with than Prima::TextView.
#
sub format_data_as_pod {
  my ($data) = @_;
  my $pod = "=pod\n\n";
  $pod .= sprintf("B<%s> = %d\n\n", $_, $data->{$_})
    for sort keys %$data;
  $pod .= "=cut\n\n";
  return $pod;
}

# Here's the GUI...
#
MAIN: {
  use Prima qw( Application Buttons FileDialog PodView );

  my $mw = Prima::MainWindow->new(
    text   => 'Vowel Counter',
    size   => [ 300, 200 ],
  );

  $mw->insert(
    Button => (
      centered  => 1,
      text      => 'Choose file',
      onClick   => sub {
        my $open = Prima::OpenDialog->new(
          filter => [
            [ 'Text files' => '*.txt' ],
            [ 'All files'  => '*' ],
          ],
        );
        if ( $open->execute ) {
          my $filename = $open->fileName;
          open(my $handle, '<', $filename)
            or die("Could not open selected file: $?");

          my $data   = get_data_from_file($handle);
          my $report = format_data_as_pod($data);

          my $report_window = Prima::Window->create(
            text  => "Report for $filename",
            size  => [ 200, 300 ],
          );

          my $pod = $report_window->insert(
            PodView => (
              pack => { expand => 1, fill => 'both' },
            ),
          );
          $pod->open_read;
          $pod->read($report);
          $pod->close_read;
        }
        else {
          die("No file chosen");
        }
      },
    ),
  );

  Prima->run;
}

如果您将前两个函数分解为它们自己的模块,那么不仅提供调用它们的 GUI 应用程序,而且还提供用于命令行使用的替代的基于文本的 UI,这将非常容易。

关于c++ - 如何从 C++ 调用 perl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259994/

相关文章:

java - Perl 或 Java 端口上运行的应用程序的名称

perl - 如何从 Perl 中的 IP 地址和网络掩码计算广播 IP?

c - 为什么将函数作为函数的参数传递?

c++ - 读取bmp文件中的像素值

c++ - 动态更改 QLineEdit TextBox 的内部循环

c++ - 多线程文件流

c++ - 是否需要 LD_LIBRARY_PATH(linux) 或 DYLD_LIBRARY_PATH mac

c++ - 派生类成员函数在 C++ 中失败

regex - Perl 正则表达式命令行问题

c - putchar 和整个代码是如何执行的?