$widget->fileevent($fh, readable => sub { if (defined(my $read = scalar <$fh>)) { # Do something with $read here } else { $widget->fileevent($fh, readable => ''); } }); #### #!/usr/bin/env perl use strict; use warnings; use autodie qw{:all}; use Tk; { my $mw = MainWindow::->new(-title => 'Test `nmap` with Tk::fileevent'); my $ctrl_F = $mw->Frame()->pack(-side => 'bottom'); my $cmd_F = $mw->Frame()->pack(-side => 'top'); my $text_F = $mw->Frame()->pack(-side => 'top', -fill => 'both', -expand => 1); my $gui_data = { start_button_text => get_start_button_text(), stop_button_text => get_stop_button_text(), button_pack_opts => [-side => 'left', -padx => 10], }; $gui_data->{out_T} = $text_F->Scrolled('Text', -scrollbars => 'osoe', -wrap => 'none', -bg => '#ffffff' )->pack(-fill => 'both', -expand => 1); sub get_button_width (); $gui_data->{start_B} = $cmd_F->Button( -textvariable => \$gui_data->{start_button_text}, -state => 'normal', -width => get_button_width(), -command => [\&start_nmap, \$mw, $gui_data], )->pack(@{$gui_data->{button_pack_opts}}); $gui_data->{stop_B} = $cmd_F->Button( -textvariable => \$gui_data->{stop_button_text}, -state => 'disabled', -width => get_button_width(), -command => [\&stop_nmap, \$mw, $gui_data], )->pack(@{$gui_data->{button_pack_opts}}); $ctrl_F->Button(-text => 'Exit', -command => sub { exit })->pack; } MainLoop; { my $nmap_running; BEGIN { $nmap_running = 0 } { my ($nmap_pipe, $nmap_pid); sub start_nmap { my ($mw, $gui_data) = @_; $nmap_pid = open $nmap_pipe, '-|', 'nmap -A localhost'; $$mw->fileevent($nmap_pipe, readable => sub { if (defined(my $read = scalar <$nmap_pipe>)) { $gui_data->{out_T}->insert(end => $read); $gui_data->{out_T}->yview('end'); } else { stop_nmap($mw, $gui_data); } }); $nmap_running = 1; @$gui_data{qw{start_button_text stop_button_text}} = (get_start_button_text(), get_stop_button_text()); $gui_data->{start_B}->configure(-state => 'disabled'); $gui_data->{stop_B}->configure(-state => 'normal'); } sub stop_nmap { my ($mw, $gui_data) = @_; $$mw->fileevent($nmap_pipe, readable => ''); kill INT => $nmap_pid if kill 0 => $nmap_pid; $nmap_running = 0; @$gui_data{qw{start_button_text stop_button_text}} = (get_start_button_text(), get_stop_button_text()); $gui_data->{start_B}->configure(-state => 'normal'); $gui_data->{stop_B}->configure(-state => 'disabled'); } } { my (@start_button_texts, @stop_button_texts); BEGIN { @start_button_texts = ('Start `nmap`', '`nmap` running ...'); @stop_button_texts = ('`nmap` not running', 'Stop `nmap`'); } sub get_start_button_text { $start_button_texts[$nmap_running] } sub get_stop_button_text { $stop_button_texts[$nmap_running] } sub get_button_width () { length +(sort { length $b <=> length $a } @start_button_texts, @stop_button_texts)[0]; } } }