in reply to Re^2: Perl tk - How to integrate external scripts
in thread Perl tk - How to integrate external scripts

You are going to need the pass the file name to the get_statistics subroutine when you call it, which means you probably are going to need to save it in a globally accessible variable. You really should also be checking for definedness / existence of the file and success on open too. Also good practice to use lexical file handles and 3 argument opens. (Not critical but they can help avoid subtle bugs.)

my $current_file;
$mw-> Button (-text =>'Get Statistics', -command =>\&get_statistics($current_file));
## Fixed as pointed out by Eliya++ below.
$mw-> Button (-text =>'Get Statistics', -command => sub{ get_statistic +s($current_file)}); sub open_file { my $open = $mw->getOpenFile( -filetypes => $types_OPEN, -defaultextension => '.sff' ); if (defined $open and -e $open){ $te->Load( "$open"); $current_file = $open; } sub get_statistics { # blah blah my $fastaFile = shift; unless (defined $fastaFile){ warn "No file name supplied.\n"; return; } open my $FASTA, '<', $fastaFile or warn "Couldn't open file: $!\n"; # blah blah while (<$FASTA>) { # blah blah
};

Replies are listed 'Best First'.
Re^4: Perl tk - How to integrate external scripts
by Eliya (Vicar) on Jan 27, 2012 at 17:46 UTC
     $mw-> Button (-text =>'Get Statistics', -command =>\&get_statistics($current_file));

    The \&get_statistics($current_file) wouldn't work, as it would call the function right away (with an empty $current_file) at the time the button is set up, and set a reference to its return value as the button callback...  In other words, \&func is quite different from \&func(), with the former being a coderef to the function.

    What you more likely want is

    $mw-> Button (-text =>'Get Statistics', -command => sub { get_statisti +cs($current_file) } );

    which would call the function with the current value of $current_file at the time the button is pressed.

    Though, as the variable is global anyway, there's no real need to pass it, so you could also leave it at

    -command => \&get_statistics

    and access $current_file directly in the routine.

    The OP's problem is primarily having made $open (i.e. the name of the selected file) scoped locally to the sub open_file, so it's not available outside of the routine.