简体   繁体   中英

perl - open windows explorer and select input file for code to work on

I would like to write a perl script that allows a user to select a file from windows explorer and use this as the input for the code within the perl script (like STDIN).

So the code would open windows explorer to the correct directory, the user would then click on (select) their file, and then the script would do it's business on the selected file as a variable (eg my $selectedFile).

I have found some code to open windows explorer:

my $explorer = 'c:/windows/SysWOW64/explorer.exe';   
my $directory = 'C:\\testdir\\';
system($explorer,$directory);

...which works fine (based on Perl monks http://www.perlmonks.org/bare/?node_id=313539 ) to open windows explorer from the pl script.

How do I get the code to then recognise the file I click on in the explorer window, and create a variable from it? Is it possible or is Perl not the way to do it?

Cheers, Matt

Here's a very bare-bones script using Win32::GUI :

use strict;
use warnings;

use Win32::GUI ();

my $file = Win32::GUI::GetOpenFileName(
    -filemustexist => 1,
);

if (defined $file) {
    print "Selected file: $file\n";
} else {
    print "Canceled\n";
}

If you don't have Win32::GUI yet ( Can't locate Win32/GUI.pm in @INC ... ), you can install it using cpan Win32::GUI , at least with Strawberry Perl . If you're using ActivePerl , I think you can get it with ppm install Win32-GUI .

Here's a very simple way using Tk .

use warnings;
use strict;

use Tk;

my $file = Tk::MainWindow->new->getOpenFile;

print "selected file: $file\n\n";

open my $fh, '<', $file or die $!;

while (<$fh>){
    print;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM