2014-06-17 37 views
1

我有一個perl程序來處理特定格式的大型文本文件。我已經準備了一個從該Perl作爲Windows控制檯應用程序的exe文件。但對於學術用途,應用程序需要用更好的GUI(C++)編寫。
我不可能再次用C++重寫整個代碼(由於時間限制)。
有沒有什麼辦法從C++ GUI取文件,使用perl App(.pl或.exe)進行處理,並再次使用C++ Window來顯示輸出。
歡迎任何其他更好的選擇。如何從C++調用perl?

+1

您是否考慮過使用[Tk](https://metacpan.org/release/Tk),[Wx](https://metacpan.org/release/Wx)或[Prima](https: //metacpan.org/release/Prima)在Perl中構建GUI,而不是使用C++創建GUI? – tobyink

+0

@tobyink即使這些也需要重寫整個代碼。而且時間太長,以至於不能這樣做。我將在未來考慮他們的另一個冒險,而不是現在。 – BioDeveloper

回答

2

下面是使用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線路使用。

+0

'Prima'的好例子。你說得對,非常容易。 +1 – Miller